﻿if exists (select 1
          from sysobjects
          where  id = object_id('dbo.BPM_Getlist')
          and type in ('P','PC'))
   drop procedure dbo.BPM_Getlist
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.CM_HotelList')
          and type in ('P','PC'))
   drop procedure dbo.CM_HotelList
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Checkresv_GetResvAll')
          and type in ('P','PC'))
   drop procedure dbo.Checkresv_GetResvAll
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.ChkResvMonitor_GetResvLog')
          and type in ('P','PC'))
   drop procedure dbo.ChkResvMonitor_GetResvLog
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.ChkResvMonitor_UpdaeResvLog')
          and type in ('P','PC'))
   drop procedure dbo.ChkResvMonitor_UpdaeResvLog
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.CommonPageSelect')
          and type in ('P','PC'))
   drop procedure dbo.CommonPageSelect
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.DFB_UpdateResvLog')
          and type in ('P','PC'))
   drop procedure dbo.DFB_UpdateResvLog
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.DeleteCacheByHotel')
          and type in ('P','PC'))
   drop procedure dbo.DeleteCacheByHotel
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.DeleteCacheByHotel2')
          and type in ('P','PC'))
   drop procedure dbo.DeleteCacheByHotel2
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.DeleteHcache')
          and type in ('P','PC'))
   drop procedure dbo.DeleteHcache
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.DeleteOldCache')
          and type in ('P','PC'))
   drop procedure dbo.DeleteOldCache
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.ECCCnumber')
          and type in ('IF', 'FN', 'TF'))
   drop function dbo.ECCCnumber
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_CheckDFBRate')
          and type in ('P','PC'))
   drop procedure dbo.Expo_CheckDFBRate
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_CheckMonthPriceRate')
          and type in ('P','PC'))
   drop procedure dbo.Expo_CheckMonthPriceRate
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_CheckRate')
          and type in ('P','PC'))
   drop procedure dbo.Expo_CheckRate
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_GetArticle')
          and type in ('P','PC'))
   drop procedure dbo.Expo_GetArticle
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_GetChildUserInfo')
          and type in ('P','PC'))
   drop procedure dbo.Expo_GetChildUserInfo
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_GetDFBPlanCode')
          and type in ('P','PC'))
   drop procedure dbo.Expo_GetDFBPlanCode
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_GetDFBPlanRate')
          and type in ('P','PC'))
   drop procedure dbo.Expo_GetDFBPlanRate
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_GetHotel')
          and type in ('P','PC'))
   drop procedure dbo.Expo_GetHotel
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_GetMonthMinPrice')
          and type in ('P','PC'))
   drop procedure dbo.Expo_GetMonthMinPrice
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_GetMonthPriceInMonth')
          and type in ('P','PC'))
   drop procedure dbo.Expo_GetMonthPriceInMonth
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_GetMonthPricePlanCode')
          and type in ('P','PC'))
   drop procedure dbo.Expo_GetMonthPricePlanCode
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_GetMonthPricePlanRate')
          and type in ('P','PC'))
   drop procedure dbo.Expo_GetMonthPricePlanRate
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_GetPagingRecord')
          and type in ('P','PC'))
   drop procedure dbo.Expo_GetPagingRecord
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_GetPlanCode')
          and type in ('P','PC'))
   drop procedure dbo.Expo_GetPlanCode
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_GetPlanRate')
          and type in ('P','PC'))
   drop procedure dbo.Expo_GetPlanRate
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_GetResv')
          and type in ('P','PC'))
   drop procedure dbo.Expo_GetResv
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_GetResvAll')
          and type in ('P','PC'))
   drop procedure dbo.Expo_GetResvAll
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_GetResvAllen')
          and type in ('P','PC'))
   drop procedure dbo.Expo_GetResvAllen
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_GetUserInfo')
          and type in ('P','PC'))
   drop procedure dbo.Expo_GetUserInfo
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_GetUserInfo_ParentId')
          and type in ('P','PC'))
   drop procedure dbo.Expo_GetUserInfo_ParentId
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_GetUserInfo_UserID')
          and type in ('P','PC'))
   drop procedure dbo.Expo_GetUserInfo_UserID
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_Hotel_CheckRate_H_cache')
          and type in ('P','PC'))
   drop procedure dbo.Expo_Hotel_CheckRate_H_cache
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_ResvLog_Add')
          and type in ('P','PC'))
   drop procedure dbo.Expo_ResvLog_Add
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_ResvLog_Add_Special')
          and type in ('P','PC'))
   drop procedure dbo.Expo_ResvLog_Add_Special
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_ResvLog_Addstat')
          and type in ('P','PC'))
   drop procedure dbo.Expo_ResvLog_Addstat
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_ResvLog_Mod')
          and type in ('P','PC'))
   drop procedure dbo.Expo_ResvLog_Mod
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_ResvLog_Sel')
          and type in ('P','PC'))
   drop procedure dbo.Expo_ResvLog_Sel
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_Resvlog_UpdatePmsRoom')
          and type in ('P','PC'))
   drop procedure dbo.Expo_Resvlog_UpdatePmsRoom
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_SearchDFBHotel')
          and type in ('P','PC'))
   drop procedure dbo.Expo_SearchDFBHotel
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_SearchHotel')
          and type in ('P','PC'))
   drop procedure dbo.Expo_SearchHotel
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_SearchMonthPriceHotel')
          and type in ('P','PC'))
   drop procedure dbo.Expo_SearchMonthPriceHotel
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_Searchapply')
          and type in ('P','PC'))
   drop procedure dbo.Expo_Searchapply
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_SelectCXL')
          and type in ('P','PC'))
   drop procedure dbo.Expo_SelectCXL
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_SelectGUA')
          and type in ('P','PC'))
   drop procedure dbo.Expo_SelectGUA
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_SelectHotel')
          and type in ('P','PC'))
   drop procedure dbo.Expo_SelectHotel
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_SelectTAX')
          and type in ('P','PC'))
   drop procedure dbo.Expo_SelectTAX
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_Sendsms')
          and type in ('P','PC'))
   drop procedure dbo.Expo_Sendsms
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_UpdateLog')
          and type in ('P','PC'))
   drop procedure dbo.Expo_UpdateLog
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_UpdateResvLog')
          and type in ('P','PC'))
   drop procedure dbo.Expo_UpdateResvLog
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Expo_User_Add')
          and type in ('P','PC'))
   drop procedure dbo.Expo_User_Add
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Exptia_GetResvAll_byName')
          and type in ('P','PC'))
   drop procedure dbo.Exptia_GetResvAll_byName
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.FGB_GetEmailIsValidateCode')
          and type in ('P','PC'))
   drop procedure dbo.FGB_GetEmailIsValidateCode
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.FGB_GetResvAll')
          and type in ('P','PC'))
   drop procedure dbo.FGB_GetResvAll
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.FGB_GetUserIsValidateCode')
          and type in ('P','PC'))
   drop procedure dbo.FGB_GetUserIsValidateCode
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.FGB_JJ_GetPagingRecord')
          and type in ('P','PC'))
   drop procedure dbo.FGB_JJ_GetPagingRecord
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.FGB_JJ_GetResv')
          and type in ('P','PC'))
   drop procedure dbo.FGB_JJ_GetResv
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.FGB_JJ_GetResvAll')
          and type in ('P','PC'))
   drop procedure dbo.FGB_JJ_GetResvAll
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.FGB_JJ_ResvLog_Add')
          and type in ('P','PC'))
   drop procedure dbo.FGB_JJ_ResvLog_Add
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.FGB_JJ_ResvLog_Mod')
          and type in ('P','PC'))
   drop procedure dbo.FGB_JJ_ResvLog_Mod
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.FGB_JJ_ResvLog_Sel')
          and type in ('P','PC'))
   drop procedure dbo.FGB_JJ_ResvLog_Sel
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.FGB_JJ_SelectTAX')
          and type in ('P','PC'))
   drop procedure dbo.FGB_JJ_SelectTAX
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.FGB_JJ_selectHotel')
          and type in ('P','PC'))
   drop procedure dbo.FGB_JJ_selectHotel
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.FGB_hweb_user_Insert_Web')
          and type in ('P','PC'))
   drop procedure dbo.FGB_hweb_user_Insert_Web
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.FGB_hweb_user_IsExist')
          and type in ('P','PC'))
   drop procedure dbo.FGB_hweb_user_IsExist
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.FITEN_GetPage')
          and type in ('P','PC'))
   drop procedure dbo.FITEN_GetPage
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.FITJSon_GetResvAll_byName')
          and type in ('P','PC'))
   drop procedure dbo.FITJSon_GetResvAll_byName
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.FITJson_MailGetResvAll_GUID')
          and type in ('P','PC'))
   drop procedure dbo.FITJson_MailGetResvAll_GUID
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.FIT_BookingRecord')
          and type in ('P','PC'))
   drop procedure dbo.FIT_BookingRecord
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.FIT_ChangeDate')
          and type in ('IF', 'FN', 'TF'))
   drop function dbo.FIT_ChangeDate
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.FIT_ChangeTime')
          and type in ('IF', 'FN', 'TF'))
   drop function dbo.FIT_ChangeTime
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.FIT_GetResvAll')
          and type in ('P','PC'))
   drop procedure dbo.FIT_GetResvAll
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.FIT_GetResvAll_byName')
          and type in ('P','PC'))
   drop procedure dbo.FIT_GetResvAll_byName
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.FIT_GetUserInfoPage')
          and type in ('P','PC'))
   drop procedure dbo.FIT_GetUserInfoPage
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.FIT_GetUserInfoPage2')
          and type in ('P','PC'))
   drop procedure dbo.FIT_GetUserInfoPage2
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.FIT_GetUserInfoPage_1')
          and type in ('P','PC'))
   drop procedure dbo.FIT_GetUserInfoPage_1
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.FIT_MailGetResvAll')
          and type in ('P','PC'))
   drop procedure dbo.FIT_MailGetResvAll
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.FIT_MailGetResvAll_GUID')
          and type in ('P','PC'))
   drop procedure dbo.FIT_MailGetResvAll_GUID
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.FIT_MailGetResvAll_googleorderno')
          and type in ('P','PC'))
   drop procedure dbo.FIT_MailGetResvAll_googleorderno
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.FIT_MemberOrdersList')
          and type in ('P','PC'))
   drop procedure dbo.FIT_MemberOrdersList
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.FIT_OVS_GetPage')
          and type in ('P','PC'))
   drop procedure dbo.FIT_OVS_GetPage
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.FIT_OverSeas_ResvLog_Add_Payment')
          and type in ('P','PC'))
   drop procedure dbo.FIT_OverSeas_ResvLog_Add_Payment
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.FIT_OverSeas_ResvLog_Add_Payment_Mod')
          and type in ('P','PC'))
   drop procedure dbo.FIT_OverSeas_ResvLog_Add_Payment_Mod
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.FIT_ResvLog_Add_Payment')
          and type in ('P','PC'))
   drop procedure dbo.FIT_ResvLog_Add_Payment
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.FIT_ResvLog_Add_Payment_Card')
          and type in ('P','PC'))
   drop procedure dbo.FIT_ResvLog_Add_Payment_Card
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.FIT_ResvLog_Sel')
          and type in ('P','PC'))
   drop procedure dbo.FIT_ResvLog_Sel
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.FIT_UserLog_GetIP')
          and type in ('P','PC'))
   drop procedure dbo.FIT_UserLog_GetIP
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.FIT_UserLog_Insert')
          and type in ('P','PC'))
   drop procedure dbo.FIT_UserLog_Insert
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.GetCCCardName')
          and type in ('IF', 'FN', 'TF'))
   drop function dbo.GetCCCardName
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.GetCCCardNames')
          and type in ('IF', 'FN', 'TF'))
   drop function dbo.GetCCCardNames
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.GetCCMail')
          and type in ('P','PC'))
   drop procedure dbo.GetCCMail
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.GetChildUserInfo')
          and type in ('P','PC'))
   drop procedure dbo.GetChildUserInfo
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.GetFIT_Profile')
          and type in ('P','PC'))
   drop procedure dbo.GetFIT_Profile
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.GetHotelInfo')
          and type in ('P','PC'))
   drop procedure dbo.GetHotelInfo
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.GetLogInfo')
          and type in ('P','PC'))
   drop procedure dbo.GetLogInfo
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.GetNotInID')
          and type in ('IF', 'FN', 'TF'))
   drop function dbo.GetNotInID
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.GetPagingRecord')
          and type in ('P','PC'))
   drop procedure dbo.GetPagingRecord
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.GetPlanCode')
          and type in ('P','PC'))
   drop procedure dbo.GetPlanCode
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.GetPlanCodeDFBCO')
          and type in ('P','PC'))
   drop procedure dbo.GetPlanCodeDFBCO
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.GetPlanCodeNew')
          and type in ('P','PC'))
   drop procedure dbo.GetPlanCodeNew
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.GetPlanCodePrice')
          and type in ('P','PC'))
   drop procedure dbo.GetPlanCodePrice
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.GetPlanRate')
          and type in ('P','PC'))
   drop procedure dbo.GetPlanRate
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.GetPlanRatetemp')
          and type in ('P','PC'))
   drop procedure dbo.GetPlanRatetemp
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.GetRecordByPage')
          and type in ('P','PC'))
   drop procedure dbo.GetRecordByPage
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.GetResv')
          and type in ('P','PC'))
   drop procedure dbo.GetResv
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.GetResvAll')
          and type in ('P','PC'))
   drop procedure dbo.GetResvAll
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.GetResvAll_Booking')
          and type in ('P','PC'))
   drop procedure dbo.GetResvAll_Booking
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.GetResvConfnum')
          and type in ('P','PC'))
   drop procedure dbo.GetResvConfnum
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.GetTaInfo')
          and type in ('P','PC'))
   drop procedure dbo.GetTaInfo
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.GetUserInfo')
          and type in ('P','PC'))
   drop procedure dbo.GetUserInfo
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.GetUserInfo_ParentId')
          and type in ('P','PC'))
   drop procedure dbo.GetUserInfo_ParentId
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.GetUserInfo_UserID')
          and type in ('P','PC'))
   drop procedure dbo.GetUserInfo_UserID
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Get_FIT_HotelComment_List')
          and type in ('P','PC'))
   drop procedure dbo.Get_FIT_HotelComment_List
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Get_FIT_HotelComment_Result')
          and type in ('P','PC'))
   drop procedure dbo.Get_FIT_HotelComment_Result
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Get_FIT_MobileValidate')
          and type in ('P','PC'))
   drop procedure dbo.Get_FIT_MobileValidate
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Get_TA_CorpHotelPrice')
          and type in ('P','PC'))
   drop procedure dbo.Get_TA_CorpHotelPrice
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Get_TA_CorpHotelPrice_e')
          and type in ('P','PC'))
   drop procedure dbo.Get_TA_CorpHotelPrice_e
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.HFG_GetEmailIsValidateCode')
          and type in ('P','PC'))
   drop procedure dbo.HFG_GetEmailIsValidateCode
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.HFG_GetPagingRecord')
          and type in ('P','PC'))
   drop procedure dbo.HFG_GetPagingRecord
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.HFG_GetResvAll')
          and type in ('P','PC'))
   drop procedure dbo.HFG_GetResvAll
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.HFG_GetResvAll_Admin')
          and type in ('P','PC'))
   drop procedure dbo.HFG_GetResvAll_Admin
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.HFG_GetUserIsValidateCode')
          and type in ('P','PC'))
   drop procedure dbo.HFG_GetUserIsValidateCode
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.HFG_ResvLog_Add')
          and type in ('P','PC'))
   drop procedure dbo.HFG_ResvLog_Add
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.HFG_UpdateResvlog_confnum')
          and type in ('P','PC'))
   drop procedure dbo.HFG_UpdateResvlog_confnum
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.HFG_UserInfo')
          and type in ('P','PC'))
   drop procedure dbo.HFG_UserInfo
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.HFG_UserIsExist')
          and type in ('P','PC'))
   drop procedure dbo.HFG_UserIsExist
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.HFG_UserResetPwd')
          and type in ('P','PC'))
   drop procedure dbo.HFG_UserResetPwd
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.HFG_User_Log')
          and type in ('P','PC'))
   drop procedure dbo.HFG_User_Log
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.HFG_hfg_user_Insert_Web')
          and type in ('P','PC'))
   drop procedure dbo.HFG_hfg_user_Insert_Web
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.HFG_hfg_user_IsExist')
          and type in ('P','PC'))
   drop procedure dbo.HFG_hfg_user_IsExist
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Hotel_CheckRate_H_cache')
          and type in ('P','PC'))
   drop procedure dbo.Hotel_CheckRate_H_cache
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Hotel_CheckRate_H_cache_bookingengine')
          and type in ('P','PC'))
   drop procedure dbo.Hotel_CheckRate_H_cache_bookingengine
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Hotel_CheckRate_H_cache_mod')
          and type in ('P','PC'))
   drop procedure dbo.Hotel_CheckRate_H_cache_mod
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Hubs1_AddResvsms')
          and type in ('P','PC'))
   drop procedure dbo.Hubs1_AddResvsms
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Hubs1_Addsendsms')
          and type in ('P','PC'))
   drop procedure dbo.Hubs1_Addsendsms
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Hubs1_Addsubsms')
          and type in ('P','PC'))
   drop procedure dbo.Hubs1_Addsubsms
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Hubs1_Sendsms')
          and type in ('P','PC'))
   drop procedure dbo.Hubs1_Sendsms
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Hubs_GetPage')
          and type in ('P','PC'))
   drop procedure dbo.Hubs_GetPage
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Hubs_HotHotelResult_TopCity')
          and type in ('P','PC'))
   drop procedure dbo.Hubs_HotHotelResult_TopCity
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Hubs_HotHotelResult_TopHotel')
          and type in ('P','PC'))
   drop procedure dbo.Hubs_HotHotelResult_TopHotel
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Hubs_HotHotelResult_Insert')
          and type in ('P','PC'))
   drop procedure dbo.Hubs_HotHotelResult_Insert
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Hubs_HotHotelResult_TopHotel_DFB')
          and type in ('P','PC'))
   drop procedure dbo.Hubs_HotHotelResult_TopHotel_DFB
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Hubs_HotHotelResult_Insert_DFB')
          and type in ('P','PC'))
   drop procedure dbo.Hubs_HotHotelResult_Insert_DFB
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Insert_FIT_CMB_MobileValidate')
          and type in ('P','PC'))
   drop procedure dbo.Insert_FIT_CMB_MobileValidate
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Insert_FIT_MobileValidate')
          and type in ('P','PC'))
   drop procedure dbo.Insert_FIT_MobileValidate
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Insert_FIT_SHZAir_MobileValidate')
          and type in ('P','PC'))
   drop procedure dbo.Insert_FIT_SHZAir_MobileValidate
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Pay_GetChinaPay_BillNO')
          and type in ('IF', 'FN', 'TF'))
   drop function dbo.Pay_GetChinaPay_BillNO
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.ResvLog_Add')
          and type in ('P','PC'))
   drop procedure dbo.ResvLog_Add
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.ResvLog_Add1')
          and type in ('P','PC'))
   drop procedure dbo.ResvLog_Add1
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.ResvLog_Add_Payment')
          and type in ('P','PC'))
   drop procedure dbo.ResvLog_Add_Payment
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.ResvLog_Add_stat')
          and type in ('P','PC'))
   drop procedure dbo.ResvLog_Add_stat
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.ResvLog_Mod')
          and type in ('P','PC'))
   drop procedure dbo.ResvLog_Mod
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.ResvLog_Sel')
          and type in ('P','PC'))
   drop procedure dbo.ResvLog_Sel
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Resvlog_Update_CheckResv')
          and type in ('P','PC'))
   drop procedure dbo.Resvlog_Update_CheckResv
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Resvlog_Update_PmsRoom')
          and type in ('P','PC'))
   drop procedure dbo.Resvlog_Update_PmsRoom
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.SearchHotel')
          and type in ('P','PC'))
   drop procedure dbo.SearchHotel
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.SearchHotel2')
          and type in ('P','PC'))
   drop procedure dbo.SearchHotel2
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.SearchHotel3')
          and type in ('P','PC'))
   drop procedure dbo.SearchHotel3
go

if exists (select 1
          from sysobjects
          where  id = object_id('SearchHotel4')
          and type in ('P','PC'))
   drop procedure SearchHotel4
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.SearchHotelDFB')
          and type in ('P','PC'))
   drop procedure dbo.SearchHotelDFB
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.SearchHotelInfo')
          and type in ('P','PC'))
   drop procedure dbo.SearchHotelInfo
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.SearchHotelNews')
          and type in ('P','PC'))
   drop procedure dbo.SearchHotelNews
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.SearchHotel_Custom')
          and type in ('P','PC'))
   drop procedure dbo.SearchHotel_Custom
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.SearchHotel_FITOVS_Hotel')
          and type in ('P','PC'))
   drop procedure dbo.SearchHotel_FITOVS_Hotel
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.SearchHotel_FIT_Hotel')
          and type in ('P','PC'))
   drop procedure dbo.SearchHotel_FIT_Hotel
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.SearchHotel_QuYu')
          and type in ('P','PC'))
   drop procedure dbo.SearchHotel_QuYu
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.SearchHotel_QuYuDFBnew')
          and type in ('P','PC'))
   drop procedure dbo.SearchHotel_QuYuDFBnew
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.SearchHotel_QuYuFIT_City')
          and type in ('P','PC'))
   drop procedure dbo.SearchHotel_QuYuFIT_City
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.SelectCXL')
          and type in ('P','PC'))
   drop procedure dbo.SelectCXL
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.SelectGUA')
          and type in ('P','PC'))
   drop procedure dbo.SelectGUA
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.SelectTAX')
          and type in ('P','PC'))
   drop procedure dbo.SelectTAX
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.SelectTAXDFB')
          and type in ('P','PC'))
   drop procedure dbo.SelectTAXDFB
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.SetFIT_Profile')
          and type in ('P','PC'))
   drop procedure dbo.SetFIT_Profile
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.Set_FIT_CityKeyWords')
          and type in ('P','PC'))
   drop procedure dbo.Set_FIT_CityKeyWords
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.UserDemo')
          and type in ('P','PC'))
   drop procedure dbo.UserDemo
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.User_Add')
          and type in ('P','PC'))
   drop procedure dbo.User_Add
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.air_chinapay')
          and type in ('P','PC'))
   drop procedure dbo.air_chinapay
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.air_chinapayreturn')
          and type in ('P','PC'))
   drop procedure dbo.air_chinapayreturn
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.andy_test')
          and type in ('P','PC'))
   drop procedure dbo.andy_test
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.chooseSendMessage')
          and type in ('P','PC'))
   drop procedure dbo.chooseSendMessage
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.dt_addtosourcecontrol_u')
          and type in ('P','PC'))
   drop procedure dbo.dt_addtosourcecontrol_u
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.dt_addtosourcecontrol')
          and type in ('P','PC'))
   drop procedure dbo.dt_addtosourcecontrol
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.dt_adduserobject')
          and type in ('P','PC'))
   drop procedure dbo.dt_adduserobject
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.dt_adduserobject_vcs')
          and type in ('P','PC'))
   drop procedure dbo.dt_adduserobject_vcs
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.dt_checkinobject_u')
          and type in ('P','PC'))
   drop procedure dbo.dt_checkinobject_u
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.dt_checkinobject')
          and type in ('P','PC'))
   drop procedure dbo.dt_checkinobject
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.dt_checkoutobject_u')
          and type in ('P','PC'))
   drop procedure dbo.dt_checkoutobject_u
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.dt_checkoutobject')
          and type in ('P','PC'))
   drop procedure dbo.dt_checkoutobject
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.dt_displayoaerror_u')
          and type in ('P','PC'))
   drop procedure dbo.dt_displayoaerror_u
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.dt_isundersourcecontrol_u')
          and type in ('P','PC'))
   drop procedure dbo.dt_isundersourcecontrol_u
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.dt_isundersourcecontrol')
          and type in ('P','PC'))
   drop procedure dbo.dt_isundersourcecontrol
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.dt_validateloginparams_u')
          and type in ('P','PC'))
   drop procedure dbo.dt_validateloginparams_u
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.dt_validateloginparams')
          and type in ('P','PC'))
   drop procedure dbo.dt_validateloginparams
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.dt_whocheckedout_u')
          and type in ('P','PC'))
   drop procedure dbo.dt_whocheckedout_u
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.dt_whocheckedout')
          and type in ('P','PC'))
   drop procedure dbo.dt_whocheckedout
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.dt_displayoaerror')
          and type in ('P','PC'))
   drop procedure dbo.dt_displayoaerror
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.dt_removefromsourcecontrol')
          and type in ('P','PC'))
   drop procedure dbo.dt_removefromsourcecontrol
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.dt_droppropertiesbyid')
          and type in ('P','PC'))
   drop procedure dbo.dt_droppropertiesbyid
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.dt_dropuserobjectbyid')
          and type in ('P','PC'))
   drop procedure dbo.dt_dropuserobjectbyid
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.dt_setpropertybyid_u')
          and type in ('P','PC'))
   drop procedure dbo.dt_setpropertybyid_u
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.dt_generateansiname')
          and type in ('P','PC'))
   drop procedure dbo.dt_generateansiname
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.dt_getobjwithprop')
          and type in ('P','PC'))
   drop procedure dbo.dt_getobjwithprop
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.dt_getobjwithprop_u')
          and type in ('P','PC'))
   drop procedure dbo.dt_getobjwithprop_u
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.dt_getpropertiesbyid')
          and type in ('P','PC'))
   drop procedure dbo.dt_getpropertiesbyid
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.dt_getpropertiesbyid_u')
          and type in ('P','PC'))
   drop procedure dbo.dt_getpropertiesbyid_u
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.dt_getpropertiesbyid_vcs_u')
          and type in ('P','PC'))
   drop procedure dbo.dt_getpropertiesbyid_vcs_u
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.dt_getpropertiesbyid_vcs')
          and type in ('P','PC'))
   drop procedure dbo.dt_getpropertiesbyid_vcs
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.dt_setpropertybyid')
          and type in ('P','PC'))
   drop procedure dbo.dt_setpropertybyid
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.dt_vcsenabled')
          and type in ('P','PC'))
   drop procedure dbo.dt_vcsenabled
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.dt_verstamp006')
          and type in ('P','PC'))
   drop procedure dbo.dt_verstamp006
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.dt_verstamp007')
          and type in ('P','PC'))
   drop procedure dbo.dt_verstamp007
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.fit_card_resvlog_add')
          and type in ('P','PC'))
   drop procedure dbo.fit_card_resvlog_add
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.getArticle')
          and type in ('P','PC'))
   drop procedure dbo.getArticle
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.getCustomLen')
          and type in ('P','PC'))
   drop procedure dbo.getCustomLen
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.get_ACFeedback')
          and type in ('P','PC'))
   drop procedure dbo.get_ACFeedback
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.get_AcCompay')
          and type in ('P','PC'))
   drop procedure dbo.get_AcCompay
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.getfit_engine_domain')
          and type in ('P','PC'))
   drop procedure dbo.getfit_engine_domain
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.gethotelrateplan')
          and type in ('P','PC'))
   drop procedure dbo.gethotelrateplan
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.hfg_addelement')
          and type in ('IF', 'FN', 'TF'))
   drop function dbo.hfg_addelement
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.hfg_applypresent')
          and type in ('P','PC'))
   drop procedure dbo.hfg_applypresent
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.hfg_applypresentfogok')
          and type in ('P','PC'))
   drop procedure dbo.hfg_applypresentfogok
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.hfg_applypresentrollback')
          and type in ('P','PC'))
   drop procedure dbo.hfg_applypresentrollback
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.hfg_batchcardnumberinsert')
          and type in ('P','PC'))
   drop procedure dbo.hfg_batchcardnumberinsert
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.hfg_buyscore')
          and type in ('P','PC'))
   drop procedure dbo.hfg_buyscore
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.hfg_cardnumberdistribute')
          and type in ('P','PC'))
   drop procedure dbo.hfg_cardnumberdistribute
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.hfg_getscorerate')
          and type in ('P','PC'))
   drop procedure dbo.hfg_getscorerate
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.hfg_getuserscore')
          and type in ('P','PC'))
   drop procedure dbo.hfg_getuserscore
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.hfg_getuserscorefreeze')
          and type in ('P','PC'))
   drop procedure dbo.hfg_getuserscorefreeze
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.hfg_hotelreport')
          and type in ('P','PC'))
   drop procedure dbo.hfg_hotelreport
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.hfg_hotelreportall')
          and type in ('P','PC'))
   drop procedure dbo.hfg_hotelreportall
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.hfg_levelcount')
          and type in ('P','PC'))
   drop procedure dbo.hfg_levelcount
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.hfg_pagination')
          and type in ('P','PC'))
   drop procedure dbo.hfg_pagination
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.hfg_paginationc')
          and type in ('P','PC'))
   drop procedure dbo.hfg_paginationc
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.hfg_presentcode')
          and type in ('IF', 'FN', 'TF'))
   drop function dbo.hfg_presentcode
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.hfg_report')
          and type in ('P','PC'))
   drop procedure dbo.hfg_report
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.hfg_reportall')
          and type in ('P','PC'))
   drop procedure dbo.hfg_reportall
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.hfg_updateuserscore')
          and type in ('P','PC'))
   drop procedure dbo.hfg_updateuserscore
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.hfg_userscore')
          and type in ('P','PC'))
   drop procedure dbo.hfg_userscore
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.hfg_userscorestat')
          and type in ('P','PC'))
   drop procedure dbo.hfg_userscorestat
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.hfg_userupgrade')
          and type in ('P','PC'))
   drop procedure dbo.hfg_userupgrade
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.hotel_search')
          and type in ('P','PC'))
   drop procedure dbo.hotel_search
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.pro_GetHotelList')
          and type in ('P','PC'))
   drop procedure dbo.pro_GetHotelList
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.pro_GetHotelList2')
          and type in ('P','PC'))
   drop procedure dbo.pro_GetHotelList2
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.pro_In_Ac_feedback')
          and type in ('P','PC'))
   drop procedure dbo.pro_In_Ac_feedback
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.pro_Mod_Ac_feedback')
          and type in ('P','PC'))
   drop procedure dbo.pro_Mod_Ac_feedback
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.pro_UpdateLog')
          and type in ('P','PC'))
   drop procedure dbo.pro_UpdateLog
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.pro_checkResult')
          and type in ('P','PC'))
   drop procedure dbo.pro_checkResult
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.pro_getScore')
          and type in ('P','PC'))
   drop procedure dbo.pro_getScore
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.pro_getnoshow')
          and type in ('P','PC'))
   drop procedure dbo.pro_getnoshow
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.pro_insertAc_BalOrder')
          and type in ('P','PC'))
   drop procedure dbo.pro_insertAc_BalOrder
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.pro_insertBalOrder')
          and type in ('P','PC'))
   drop procedure dbo.pro_insertBalOrder
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.pro_insertComPay')
          and type in ('P','PC'))
   drop procedure dbo.pro_insertComPay
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.pro_insertR_OverTime')
          and type in ('P','PC'))
   drop procedure dbo.pro_insertR_OverTime
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.selectHotel')
          and type in ('P','PC'))
   drop procedure dbo.selectHotel
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.setFeedBack')
          and type in ('P','PC'))
   drop procedure dbo.setFeedBack
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.sms_send_Add')
          and type in ('P','PC'))
   drop procedure dbo.sms_send_Add
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.sp_GetHotelDetail_3')
          and type in ('P','PC'))
   drop procedure dbo.sp_GetHotelDetail_3
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.sp_GetPlanCodeDFBCO')
          and type in ('P','PC'))
   drop procedure dbo.sp_GetPlanCodeDFBCO
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.sp_GetPlanRate')
          and type in ('P','PC'))
   drop procedure dbo.sp_GetPlanRate
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.sp_GetRecordByPage')
          and type in ('P','PC'))
   drop procedure dbo.sp_GetRecordByPage
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.sp_Get_Hotel_Detail')
          and type in ('P','PC'))
   drop procedure dbo.sp_Get_Hotel_Detail
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.sp_HCMS_Add_Plan')
          and type in ('P','PC'))
   drop procedure dbo.sp_HCMS_Add_Plan
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.sp_PageView')
          and type in ('P','PC'))
   drop procedure dbo.sp_PageView
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.sp_SearchHotel')
          and type in ('P','PC'))
   drop procedure dbo.sp_SearchHotel
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.sp_Search_Hotel')
          and type in ('P','PC'))
   drop procedure dbo.sp_Search_Hotel
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.sp_Search_Hotel_3')
          and type in ('P','PC'))
   drop procedure dbo.sp_Search_Hotel_3
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.sp_UpdateCache')
          and type in ('P','PC'))
   drop procedure dbo.sp_UpdateCache
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.sp_connect_oralce')
          and type in ('P','PC'))
   drop procedure dbo.sp_connect_oralce
go

if exists (select 1
          from sysobjects
          where  id = object_id('dbo.usp_PagingLarge')
          and type in ('P','PC'))
   drop procedure dbo.usp_PagingLarge
go


create procedure dbo.BPM_Getlist (
         @tablename varchar(100),
         @fieldlist varchar(4000)='*',
         @orderfield varchar(100),
         @keyfield varchar(100),
         @pageindex int,
         @pagesize int=20,
         @strwhere varchar(4000)= null ,
         @ordertype bit=1
 	
     ) as
SET NOCOUNT ON 
    declare @sqlstr varchar(6000) 
    Declare @sql nvarchar(4000);
    declare @totalRecord int;
    
    set @strwhere=replace(@strwhere,'''','''''') 
    set @strwhere=replace(@strwhere,'--','') 
    set @strwhere=replace(@strwhere,';','') 
       
  
       
   
     
        

    
    
    set @sqlstr='declare @CurPageNum int;' 
    set @sqlstr=@sqlstr+'declare @nextpagenum int;' 
    set @sqlstr=@sqlstr+'set @curpagenum='+cast(@PageIndex as varchar)+'*'+cast(@Pagesize as varchar)+';' 
    set @sqlstr=@sqlstr+'set @nextpagenum='+cast(@PageIndex+1 as varchar)+'*'+cast(@Pagesize as varchar)+';' 
    set @sqlstr=@sqlstr+'declare @sqlstr varchar(6000);' 
    if @ordertype=1 
    begin 
    set @sqlstr=@sqlstr+'set @sqlstr=''select '+@fieldlist+' from ( select top ''+cast(@nextpagenum as varchar)+'' * from  
 
'+@tablename+'  where  '+@strwhere+' order by '+@orderfield+' desc ) as a where '+@keyfield+' not in (  
 
select top ''+cast(@curpagenum as varchar)+'' '+@keyfield+' from '+@tablename+' where '+@strwhere+'  
 
order by '+@orderfield+' desc) order by '+@orderfield+' desc'';' 
    end 
    else 
    begin 
    set @sqlstr=@sqlstr+'set @sqlstr=''select '+@fieldlist+' from ( select top ''+cast(@nextpagenum as varchar)+'' * from  
 
'+@tablename+'  where '+@strwhere+' order by '+@orderfield+' asc ) as a where '+@keyfield+' not in (  
 
select top ''+cast(@curpagenum as varchar)+'' '+@keyfield+' from '+@tablename+' where '+@strwhere+'  
 
order by '+@orderfield+' asc) order by '+@orderfield+' asc'';' 
    end 
     
    set @sqlstr=@sqlstr+'execute( @sqlstr)' 
    execute(@sqlstr)
    
go


create procedure dbo.CM_HotelList @Title nvarchar(50),
 @Pid int,
 @addsql nvarchar(1000),
 @PageSize int, 
 @CurPage int, 
 @doCount int 
declare @MyTitle nvarchar(50)
    
    set @Title=replace(@Title,'''','''''') 
    set @Title=replace(@Title,'--','') 
    set @Title=replace(@Title,';','') 
set @MyTitle = '%'+@Title+'%'




declare @s varchar(6000) 
declare @stemp varchar(6000) 
if (@doCount != 0)  
begin 
set @s ='select count(*) as Total from dbo.Hotel where 1=1'
end
else
begin
set @s ='select top ' + cast(@PageSize as nvarchar(20)) + ' * from dbo.Hotel where 1=1'
end


set @stemp =''


if (@Title!='')
set @stemp =@stemp+'and (Title like '''+@MyTitle+''' or Title_e like '''+@MyTitle+''' or keywords like '''+@MyTitle+''')'

if (@Pid!=-1)
set @stemp =@stemp+' and Pid ='+ cast(@Pid as varchar)
if (@addsql!='')
set @stemp=@stemp+@addsql


if (@doCount =0)
	begin
	if (@CurPage!=1)
		
		begin
		
		declare @PageIndex int
		set @PageIndex=(@CurPage-1)*@PageSize
		set @s =@s+@stemp+' and Hotel_ID not in(select top ' + cast(@PageIndex as nvarchar(20)) + ' Hotel_ID from hotel where 1=1 '+@stemp+ ' order by city asc,hotel_id desc) order by city asc,hotel_id desc'
		end

	else
	begin
	set @s =@s+@stemp+'order by city asc,hotel_id desc'
	end
	end
else
set @s =@s+@stemp

exec ( @s )
print @s
go


create procedure dbo.Checkresv_GetResvAll @Confnum nvarchar(50) as
declare @MyConfnum nvarchar(50)
    
    set @Confnum=replace(@Confnum,'''','''''') 
    set @Confnum=replace(@Confnum,'--','') 
    set @Confnum=replace(@Confnum,';','') 
set @MyConfnum =@Confnum


SELECT resvlog.*,hotel.phone,hotel.address1,h_baseinfo.address1 as address1_e,hotel.checkin,hotel.checkout,hotel.title_e,hotel.title FROM [resvlog],[hotel],[h_baseinfo] where  confnum=@MyConfnum  and resvlog.propertyid=hotel.pid and resvlog.propertyid=h_baseinfo.pid and h_baseinfo.languagetype=1
go


create procedure dbo.ChkResvMonitor_GetResvLog @Days int=30 
SELECT *
FROM resvlog

where (((updatetime<getdate() and datediff(day,updatetime,getdate())<=@Days) and getstatus=0) or ((deptime<getdate() and datediff(day,deptime,getdate())<=10) and getstatus=8) or ((starttime<getdate() and datediff(day,starttime,getdate())<=@Days) and getstatus<>8 and getstatus<>0)) and confnum!=''
go


create procedure dbo.ChkResvMonitor_UpdaeResvLog @Confnum nvarchar(50),
 @Getstatus int,
 @Totalrevenue decimal(18,2),
 @Departure datetime,
 @status nvarchar(50),
 @pmsno varchar(100) as
update dbo.Resvlog  set Getstatus=@Getstatus,Totalrevenue=@Totalrevenue,Departure=@Departure,pmsno=@pmsno where confnum=@Confnum
go


create procedure dbo.CommonPageSelect (
  @SqlTable varchar(5000),
  @SqlColumn varchar(4000),
  @SqlWhere varchar(800)='', 
  @pagenum int=20,
  @beginline int=1, 
  @SqlPK varchar(100),
  @SqlOrder Varchar(100), 
  @Count int=0 output,
  @pageCount int =0 output
 ) as
set nocount on
declare @PageLowerBound int
declare @PageUpperBound int
declare @sqlstr nvarchar(4000)
declare @n int


 

IF @beginline=1 
BEGIN
	set @sqlstr=N'select @sCount=count(1) FROM '+@SqlTable 	
	
	if @SqlWhere !='' 
	begin
		set @sqlstr= @sqlstr +' where 1=1 '+@SqlWhere
	end 	
	print @sqlstr
	Exec sp_executesql @sqlstr,N'@sCount int outPut',@Count output

	if(CHARINDEX('Distinct ',@SqlColumn)>=0)
	begin
	   set @sqlstr= 'select  top '+Convert(varchar(10),@pagenum)+' '+REPLACE(@SqlColumn,'Distinct ',' ')+' from '+@SqlTable
	end
	else
	begin
	set @sqlstr= 'select top '+Convert(varchar(10),@pagenum)+' '+@SqlColumn+' from '+@SqlTable 
	end
	if @SqlWhere !='' 
	begin
		set @sqlstr= @sqlstr +' where 1=1 '+@SqlWhere
	end 
	if @SqlOrder !='' 
	begin
		set @sqlstr= @sqlstr +' '+@SqlOrder
	end 
	print @sqlstr
	Exec sp_executesql @sqlstr
	select @Count
    set @n = @Count/@pagenum

    if @pagenum*@n <> @Count
    begin
   set @pageCount = @n+1
    end
    else
     begin
    set @pageCount = @n
     end 
    
    
	return 
END
else
begin
	select @Count =0 
    select @pageCount =0 
end



set @PageLowerBound=(@beginline-1)*@pagenum
set @PageUpperBound=@PageLowerBound+@pagenum

create table #pageindex(rowcountid int identity(1,1) not null,pageindexpkid int)
set rowcount @PageUpperBound 
set @sqlstr=N'insert into #pageindex(pageindexpkid) select '+@SqlPK+' from '+@SqlTable
if @SqlWhere !='' 
begin
	set @sqlstr= @sqlstr +' where 1=1 '+@SqlWhere
end 
if @SqlOrder !='' 
begin
	set @sqlstr= @sqlstr +' '+@SqlOrder
end 

print @sqlstr
Exec sp_executesql @sqlstr

set @sqlstr='select '+@SqlColumn+',p.rowcountid FROM '+ @SqlTable +' inner join #pageindex p on '+@SqlPK+'=p.pageindexpkid and (p.rowcountid>'+Convert(varchar(15),@PageLowerBound)+') and (p.rowcountid<='+Convert(varchar(15),@PageUpperBound)+')' 
print @sqlstr
Exec sp_executesql @sqlstr


set nocount off
drop table #pageindex
go


create procedure dbo.DFB_UpdateResvLog @Confnum nvarchar(50),
 @Getstatus int,
 @Totalrevenue decimal,
 @Departure datetime,
 @status nvarchar(50) as
update dbo.Resvlog  set Getstatus=@Getstatus,Totalrevenue=@Totalrevenue,Departure=@Departure where confnum=@Confnum
go


create procedure dbo.DeleteCacheByHotel as
delete  H_cache from  H_cache inner  join dbo.H_TempHotel  on  dbo.H_cache.Property_id = dbo.H_TempHotel.Property_id and  dbo.H_cache.RoomCode = dbo.H_TempHotel.roomcode
go


create procedure dbo.DeleteCacheByHotel2 as
delete  temp_cache from  temp_cache inner  join dbo.H_TempHotel  on  dbo.temp_cache.Property_id = dbo.H_TempHotel.Property_id and  dbo.temp_cache.RoomCode = dbo.H_TempHotel.roomcode
go


create procedure dbo.DeleteHcache as
declare   @cdate   datetime   
select   @cdate=getdate()

delete from H_cache
where Availdate < dateadd(d,-10,@cdate)



update h_Cache set 
singlerate=Temp_Cache.singlerate ,
doublerate=Temp_Cache.doublerate ,
triplerate=Temp_Cache.triplerate ,
quadrate=Temp_Cache.quadrate ,
extraadult=Temp_Cache.extraadult ,
extrachildren=Temp_Cache.extrachildren ,
Allotment=Temp_Cache.Allotment ,
AllotMax=Temp_Cache.AllotMax ,
AvStat=Temp_Cache.AvStat ,
MaxLos=Temp_Cache.MaxLos ,
MinLos=Temp_Cache.MinLos ,
RateCode=Temp_Cache.RateCode ,
RoomCode=Temp_Cache.RoomCode ,
Tcode=Temp_Cache.Tcode ,
T_from=Temp_Cache.T_from ,
T_to=Temp_Cache.T_to ,
Roomdesc=Temp_Cache.Roomdesc ,
Ratedesc=Temp_Cache.Ratedesc ,
Gua=Temp_Cache.Gua ,
Cxl=Temp_Cache.Cxl ,
PriceNoTax=Temp_Cache.PriceNoTax ,
cutOff=Temp_Cache.cutOff 
from temp_cache where
H_cache.Property_id=Temp_Cache.Property_id and
H_cache.plancode=Temp_Cache.plancode and
H_cache.Availdate=Temp_Cache.Availdate

delete  temp_cache from  temp_cache
 inner  join  H_Cache  on  
H_cache.Property_id=Temp_Cache.Property_id and
H_cache.plancode=Temp_Cache.plancode and
H_cache.Availdate=Temp_Cache.Availdate

insert into H_Cache
(Property_id,plancode,Availdate,singlerate,doublerate,triplerate,quadrate,extraadult,extrachildren,Allotment,AllotMax,AvStat,MaxLos,MinLos,RateCode,RoomCode,Tcode,T_from,T_to,Roomdesc,Ratedesc,Gua,Cxl,PriceNoTax,cutOff)
select Property_id,plancode,Availdate,singlerate,doublerate,triplerate,quadrate,extraadult,extrachildren,Allotment,AllotMax,AvStat,MaxLos,MinLos,RateCode,RoomCode,Tcode,T_from,T_to,Roomdesc,Ratedesc,Gua,Cxl,PriceNoTax,cutOff from temp_cache;

delete temp_Cache
go


create procedure dbo.DeleteOldCache as
delete temp_cache  from H_Cache b where 
temp_cache.Property_id=b.Property_id and 
temp_cache.plancode=b.plancode and 
temp_cache.Availdate=b.Availdate and 
temp_cache.AvStat=b.AvStat and 
temp_cache.Allotment=b.Allotment and
temp_cache.RateCode=b.RateCode and 
temp_cache.RoomCode=b.RoomCode and  
temp_cache.MaxLos=b.MaxLos and 
temp_cache.MinLos=b.MinLos and 
temp_cache.Gua=b.Gua and 
temp_cache.Cxl=b.Cxl and 
temp_cache.PriceNoTax=b.PriceNoTax and 
temp_cache.Roomdesc=b.Roomdesc and 
temp_cache.Ratedesc=b.Ratedesc and 
temp_cache.cutOff=b.cutOff
go


create function dbo.ECCCnumber (@ccnumber as varchar(20))
returns nvarchar(20) 
as 
begin
declare @temp as varchar(20);
set @temp='';
declare @l as int;
set @l=len(@ccnumber);
if @l>4
begin
  set @temp=replace(space(@l-4),' ','*')+right(@ccnumber,4)  
end
else
set @temp=replace(space(@l-1),' ','*')+right(@ccnumber,1)  
return @temp;
end
go


create procedure dbo.Expo_CheckDFBRate @Property_id int,
 @plancode varchar(50),
 @Chickindate datetime,
 @Chickoutdate datetime as
select plancode as xmlallotment,plancode as xmlpricenotax, [ID],property_id,plancode,convert(nvarchar(10),AvailDate,120) AS AvailDate,gua,cxl,singlerate,doublerate,triplerate,quadrate,extraadult,extrachildren,allotment,allotmax,avstat,maxlos,minlos,ratecode,roomcode,tcode,t_from,t_to,roomdesc,ratedesc,gua,cxl,pricenotax,cutoff from h_cache where Property_id=@Property_id and Availdate>=@Chickindate and Availdate<@Chickoutdate and plancode=@plancode order by Availdate
go


create procedure dbo.Expo_CheckMonthPriceRate @Property_id int,
 @plancode varchar(50),
 @Chickindate datetime,
 @Chickoutdate datetime as
declare @CheckInTime varchar(20)
declare @CheckOutTime Varchar(20)

select @CheckInTime = convert(nvarchar,year(@Chickindate))+'-'+Convert(nvarchar,month(@Chickindate))
select @CheckOutTime = convert(nvarchar,year(@Chickoutdate))+'-'+Convert(nvarchar,month(@Chickoutdate))


select plancode as xmlallotment,plancode as xmlpricenotax, property_id,plancode,
convert(nvarchar(10),AvailDate,120) AS AvailDate,gua,cxl,singlerate,
doublerate,triplerate,quadrate,extraadult,extrachildren,allotment,allotmax,avstat,
maxlos,minlos,ratecode,roomcode,tcode,t_from,t_to,roomdesc,ratedesc,gua,cxl,pricenotax,cutoff
from expo_cache where
Property_id=@Property_id  and
(Convert(nvarchar,year(Availdate))+'-'+Convert(nvarchar,month(Availdate))) >= ''+@CheckInTime+'' and 
(Convert(nvarchar,year(Availdate))+'-'+Convert(nvarchar,month(Availdate))) <=''+@CheckOutTime+''
and plancode=@plancode order by Availdate
go


create procedure dbo.Expo_CheckRate @Property_id int,
 @plancode varchar(50),
 @Chickindate datetime,
 @Chickoutdate datetime as
select plancode as xmlallotment,plancode as xmlpricenotax, property_id,plancode,convert(nvarchar(10),AvailDate,120) AS AvailDate,gua,cxl,singlerate,doublerate,triplerate,quadrate,extraadult,extrachildren,allotment,allotmax,avstat,maxlos,minlos,ratecode,roomcode,tcode,t_from,t_to,roomdesc,ratedesc,gua,cxl,pricenotax,cutoff from expo_cache where Property_id=@Property_id and Availdate>=@Chickindate and Availdate<@Chickoutdate and plancode=@plancode order by Availdate
go


create procedure dbo.Expo_GetArticle @PageIndex int,
 @Pagesize int,
 @language nvarchar(10) as
declare @sql varchar(500)
   declare @curpagenum int
   declare @nextpagenum int
   set @curpagenum=@PageIndex*@Pagesize
   set @nextpagenum=(@PageIndex)*@Pagesize
   begin
         set @sql='select top '+cast(@Pagesize as varchar)+' a.classid, a.title,a.subtitle,a.updatetime,b.ClassName,ArticleID from Article as a left join ArticleClass as b  
on a.ClassID=b.ClassID  where a.ClassID=b.ClassID and a.classid=8 and language ='+ @language +' and ArticleID not in (select  top '+cast(@nextpagenum as varchar)+' ArticleID from Article order by articleid desc) order by articleid desc'
   end 
   exec(@sql)
   print @sql
go


create procedure dbo.Expo_GetChildUserInfo @Username nvarchar(50),
 @Userid nvarchar(50) as
declare @MyUsername nvarchar(50),
        @MyUserid nvarchar(50)
    
    set @Username=replace(@Username,'''','''''') 
    set @Username=replace(@Username,'--','') 
    set @Username=replace(@Username,';','') 
    set @Userid=replace(@Userid,'''','''''') 
    set @Userid=replace(@Userid,'--','') 
    set @Userid=replace(@Userid,';','') 
set @MyUsername =@Username
set  @MyUserid=@Userid
if(@Myusername<>'')
begin
  select * from [User] where parentid =(select parentid from [User] where username=@MyUsername)
   
end
else
begin
   select * from [User] where parentid =(select parentid from [User] where userid=@MyUserid)
end
go


create procedure dbo.Expo_GetDFBPlanCode @pid nvarchar(50),
 @CheckIn datetime,
 @CheckOut datetime,
 @Plan nvarchar(500),
 @language nvarchar(10) as
declare @s varchar(6000) 
set @s='select distinct(c.plancode),c.Property_id,c.avstat,p.plandesc,p.roomdesc,p.roomname  from H_cache as c left outer join h_plan as p on  c.property_id=p.property_id and c.plancode=p.plancode and p.languagetype='+ @language +' where Allotment>=1 and c.property_id='+@pid+' and pricenotax>0 and  (datediff(hh,getdate(),c.Availdate)+24>=c.cutoff)  and availdate>='''+convert(varchar(10),@CheckIn,120)+'''  and availdate<'''+convert(varchar(10),@CheckOut,120)+ ''' and '+@Plan
exec (@s)
go


create procedure dbo.Expo_GetDFBPlanRate @PIDCode nvarchar(4000),
 @CheckIn datetime,
 @CheckOut datetime as
declare @stemp varchar(8000) 

set @stemp ='SELECT plancode,ratecode,roomcode,avstat,minlos,maxlos,gua,cxl,cutoff, Property_id,singlerate,doublerate, priceNoTax, [ID],Allotment,Availdate FROM H_cache  '



if (@PIDCode !='')
begin
set @stemp =@stemp+ ' WHERE  '+ @PIDCode 
end
else 
begin
set @stemp =@stemp+ ' WHERE 1=2  '
end

set @stemp =@stemp+ ' and  ( Availdate>= '''+convert(varchar(10),@CheckIn,120)+''' AND Availdate<'''+convert(varchar(10),@CheckOut,120)+''')  order by plancode, availdate '
print @stemp
exec ( @stemp )
go


create procedure dbo.Expo_GetHotel @Title nvarchar(50),
 @PageSize int=10, 
 @CurPage int=1, 
 @doCount int 
declare @MyTitle nvarchar(50)
    
    set @Title=replace(@Title,'''','''''') 
    set @Title=replace(@Title,'--','') 
    set @Title=replace(@Title,';','') 
set @MyTitle = '%'+@Title+'%'

declare @s varchar(6000) 
declare @stemp varchar(6000) 


if (@doCount != 0)  
begin 
set @s ='select count(*) as Total from dbo.Hotel '
end
else
begin
declare @PageIndex int
set @PageIndex=@CurPage*@PageSize

set @s ='select  top ' + cast(@PageSize as nvarchar(20)) + ' * from (select top ' + cast(@PageSize as nvarchar(20)) + ' * from (select top ' +cast(@PageIndex as nvarchar(20)) + ' * from dbo.Hotel '
end


set @stemp =''


if (@Title!='')
set @stemp =@stemp+'where (Title like '''+@MyTitle+''' or Title_e like '''+@MyTitle+''' or pid like '''+@MyTitle+''' or keywords like '''+@MyTitle+''' )'



if (@doCount =0)
begin
set @s =@s+@stemp+ ' order by credit desc, pagerank desc,hotel_id ) as aa  order by credit,pagerank ,hotel_id desc) as aa order by pid'
end
else
set @s =@s+@stemp
print @s
exec ( @s )
print @s
go


create procedure dbo.Expo_GetMonthMinPrice @CheckIn datetime,
 @CheckOut datetime,
 @RateCode nvarchar(50),
 @Property_id nvarchar(10) as
declare @CheckInTime nvarchar(20),
  @CheckOutTime nvarchar(20),
  @sql nvarchar(2000)
  
set @CheckInTime = Convert(nvarchar,year(@CheckIn)) +'-'+ Convert(nvarchar,month(@CheckIn))
set @CheckOutTime = Convert(nvarchar,year(@CheckOut)) +'-'+ Convert(nvarchar,month(@CheckOut))
set @sql = 'select min(pricenotax)as pricenotax from expo_cache where property_id = '+@property_id+' and '+@RateCode+' and pricenotax<>0'

print(@sql)
exec(@sql)
go


create procedure dbo.Expo_GetMonthPriceInMonth @CheckIn datetime,
 @CheckOut datetime,
 @Property_id nvarchar(10),
 @plancode nvarchar(50) as
declare @sql nvarchar(2000)

declare @CheckInTime varchar(20)
declare @CheckOutTime Varchar(20)

select @CheckInTime = convert(nvarchar,year(@CheckIn))+'-'+Convert(nvarchar,month(@CheckIn))+'-1'
select @CheckOutTime = convert(nvarchar,year(@CheckOut))+'-'+Convert(nvarchar,month(@CheckOut))+'-1'

set @sql = 'select availdate,pricenotax from expo_cache where property_id = '+@Property_id+'   and Availdate >= '''+@CheckInTime+''' and Availdate <='''+@CheckOutTime+'''  and plancode = '''+@plancode+''''



exec(@sql)
go


create procedure dbo.Expo_GetMonthPricePlanCode @pid nvarchar(50),
 @CheckIn datetime,
 @CheckOut datetime,
 @Plan nvarchar(500),
 @language nvarchar(10) as
declare @s varchar(6000) 

declare @CheckInTime varchar(20)
declare @CheckOutTime Varchar(20)

select @CheckInTime = convert(nvarchar,year(@CheckIn))+'-'+Convert(nvarchar,month(@CheckIn))
select @CheckOutTime = convert(nvarchar,year(@CheckOut))+'-'+Convert(nvarchar,month(@CheckOut))

set @s='select distinct(c.plancode),c.Property_id,p.plandesc,p.roomdesc,p.roomname from expo_cache as c left outer join h_plan as p on c.property_id=p.property_id and c.plancode=p.plancode and p.languagetype='+ @language +''
set @s=@s+' where c.property_id = '+@pid+' and (datediff(hh,getdate(),Availdate)+24>=cutoff) and '+@Plan+' and (Convert(nvarchar,year(Availdate))+''-''+Convert(nvarchar,month(Availdate))) >= '''+@CheckInTime+''' and (Convert(nvarchar,year(Availdate))+''-''+Convert(nvarchar,month(Availdate))) <='''+@CheckOutTime+''''





exec (@s)
print(@s)
go


create procedure dbo.Expo_GetMonthPricePlanRate @PIDCode nvarchar(4000),
 @CheckIn datetime,
 @CheckOut datetime as
declare @stemp varchar(8000) 

declare @CheckInTime varchar(20)
declare @CheckOutTime Varchar(20)

select @CheckInTime = convert(nvarchar,year(@CheckIn))+'-'+Convert(nvarchar,month(@CheckIn))
select @CheckOutTime = convert(nvarchar,year(@CheckOut))+'-'+Convert(nvarchar,month(@CheckOut))

set @stemp ='SELECT plancode,ratecode,roomcode,avstat,minlos,maxlos,gua,cxl,cutoff, Property_id, priceNoTax, Allotment,Availdate FROM expo_cache  '



if (@PIDCode !='')
begin
set @stemp =@stemp+ ' WHERE  '+ @PIDCode 
end
else 
begin
set @stemp =@stemp+ ' WHERE 1=2  '
end

set @stemp = @stemp +' and (Convert(nvarchar,year(Availdate))+''-''+Convert(nvarchar,month(Availdate))) >= '''+@CheckInTime+''' and (Convert(nvarchar,year(Availdate))+''-''+Convert(nvarchar,month(Availdate))) <='''+@CheckOutTime+''' order by plancode, availdate'


print @stemp
exec ( @stemp )
go


create procedure dbo.Expo_GetPagingRecord ( 
         @tablename varchar(100),
         @fieldlist varchar(4000)='*',
         @orderfield varchar(100),
         @keyfield varchar(100),
         @pageindex int,
         @pagesize int=20,
         @strwhere varchar(4000)= null ,
         @ordertype bit=1
 	
     ) as
SET NOCOUNT ON 
    declare @sqlstr varchar(6000) 
    Declare @sql nvarchar(4000);
    declare @totalRecord int;
    
    set @strwhere=replace(@strwhere,'''','''''') 
    set @strwhere=replace(@strwhere,'--','') 
    set @strwhere=replace(@strwhere,';','') 
       
  
       
   
     
        

    
    
    set @sqlstr='declare @CurPageNum int;' 
    set @sqlstr=@sqlstr+'declare @nextpagenum int;' 
    set @sqlstr=@sqlstr+'set @curpagenum='+cast(@PageIndex as varchar)+'*'+cast(@Pagesize as varchar)+';' 
    set @sqlstr=@sqlstr+'set @nextpagenum='+cast(@PageIndex+1 as varchar)+'*'+cast(@Pagesize as varchar)+';' 
    set @sqlstr=@sqlstr+'declare @sqlstr varchar(6000);' 
    if @ordertype=1 
    begin 
    set @sqlstr=@sqlstr+'set @sqlstr=''select '+@fieldlist+' from ( select top ''+cast(@nextpagenum as varchar)+'' * from  
 
'+@tablename+'  where  '+@strwhere+' order by '+@orderfield+' desc ) as a where '+@keyfield+' not in (  
 
select top ''+cast(@curpagenum as varchar)+'' '+@keyfield+' from '+@tablename+' where '+@strwhere+'  
 
order by '+@orderfield+' desc) order by '+@orderfield+' desc'';' 
    end 
    else 
    begin 
    set @sqlstr=@sqlstr+'set @sqlstr=''select '+@fieldlist+' from ( select top ''+cast(@nextpagenum as varchar)+'' * from  
 
'+@tablename+'  where '+@strwhere+' order by '+@orderfield+' asc ) as a where '+@keyfield+' not in (  
 
select top ''+cast(@curpagenum as varchar)+'' '+@keyfield+' from '+@tablename+' where '+@strwhere+'  
 
order by '+@orderfield+' asc) order by '+@orderfield+' asc'';' 
    end 
     
    set @sqlstr=@sqlstr+'execute( @sqlstr)' 
    execute(@sqlstr)
    print @sqlstr
go


create procedure dbo.Expo_GetPlanCode @pid nvarchar(50),
 @CheckIn datetime,
 @CheckOut datetime,
 @Plan nvarchar(500),
 @language nvarchar(10) as
declare @s varchar(6000) 

set @s='select distinct(c.plancode),c.Property_id,p.plandesc,p.roomdesc,p.roomname  from expo_cache as c left outer join h_plan as p on  c.property_id=p.property_id and c.plancode=p.plancode and p.languagetype='+ @language +' where Allotment>=1 and c.property_id='+@pid+' and  (datediff(hh,getdate(),c.Availdate)+24>=c.cutoff)  and availdate>='''+convert(varchar(10),@CheckIn,120)+'''  and availdate<'''+convert(varchar(10),@CheckOut,120)+ ''' and '+@Plan






--


--




exec (@s)
print(@s)
go


create procedure dbo.Expo_GetPlanRate @PIDCode nvarchar(4000),
 @CheckIn datetime,
 @CheckOut datetime as
declare @stemp varchar(8000) 

set @stemp ='SELECT plancode,ratecode,roomcode,avstat,minlos,maxlos,gua,cxl,cutoff, Property_id, singlerate,doublerate, priceNoTax, Allotment,Availdate FROM expo_cache  '



if (@PIDCode !='')
begin
set @stemp =@stemp+ ' WHERE  '+ @PIDCode 
end
else 
begin
set @stemp =@stemp+ ' WHERE 1=2  '
end

set @stemp =@stemp+ ' and  ( Availdate>= '''+convert(varchar(10),@CheckIn,120)+''' AND Availdate<'''+convert(varchar(10),@CheckOut,120)+''')  order by plancode, availdate '
print @stemp
exec ( @stemp )
go


create procedure dbo.Expo_GetResv @Confnum nvarchar(50) as
declare @MyConfnum nvarchar(50)
    
    set @Confnum=replace(@Confnum,'''','''''') 
    set @Confnum=replace(@Confnum,'--','') 
    set @Confnum=replace(@Confnum,';','') 
set @MyConfnum =@Confnum


SELECT * FROM [resvlog] where  confnum=@MyConfnum
go


create procedure dbo.Expo_GetResvAll @Confnum nvarchar(50) as
declare @MyConfnum nvarchar(50)
    
    set @Confnum=replace(@Confnum,'''','''''') 
    set @Confnum=replace(@Confnum,'--','') 
    set @Confnum=replace(@Confnum,';','') 
set @MyConfnum =@Confnum


SELECT resvlog.*,hotel.phone,hotel.address1,hotel.address1_e,hotel.checkin,hotel.checkout FROM [resvlog],[hotel] where  confnum=@MyConfnum and (resvlog.propertyid=hotel.pid or resvlog.propertyid=hotel.pid_e)
go


create procedure dbo.Expo_GetResvAllen @Confnum nvarchar(50) as
declare @MyConfnum nvarchar(50)
    
    set @Confnum=replace(@Confnum,'''','''''') 
    set @Confnum=replace(@Confnum,'--','') 
    set @Confnum=replace(@Confnum,';','') 
set @MyConfnum =@Confnum


SELECT resvlog.*,hotel.phone,hotel.address1,h_baseinfo.address1 as address1_e,hotel.checkin,hotel.checkout FROM [resvlog],[hotel],[h_baseinfo] where  confnum=@MyConfnum and (resvlog.propertyid=hotel.pid) and resvlog.propertyid=h_baseinfo.pid and h_baseinfo.languagetype=1
go


create procedure dbo.Expo_GetUserInfo @Username nvarchar(50) as
declare @MyUsername nvarchar(50)
    
    set @Username=replace(@Username,'''','''''') 
    set @Username=replace(@Username,'--','') 
    set @Username=replace(@Username,';','') 
set @MyUsername =@Username


SELECT [USER].*, Corp.Corp_Id,Corp.corp_name, Corp.corp_name_e, corp.defaultrate, corp.IATA,corp.fax,corp.sendfax, corp.credit,corp.HotelGroupID,corp.NoHotelGroup,corp.corp_ID,corp.account,corp.accounttel,corp.accountfax,corp.accountemail,corp.business,corp.bsntel,corp.bsnfax,corp.bsnemail,corp.resvcredit,corp.Corp_name_e  FROM [USER],[Corp] where  [USER].parentid = corp.corp_id and [USER].UserName=@MyUsername
go


create procedure dbo.Expo_GetUserInfo_ParentId @Parentid nvarchar(50) as
declare @Myparentid nvarchar(50)
    
    set @Parentid=replace(@Parentid,'''','''''') 
    set @Parentid=replace(@Parentid,'--','') 
    set @Parentid=replace(@Parentid,';','') 
set @Myparentid =@Parentid


SELECT [USER].*, Corp.corp_name, Corp.corp_name_e, corp.defaultrate, corp.IATA,corp.fax,corp.sendfax, corp.credit,corp.HotelGroupID,corp.corp_ID FROM [USER],[Corp] where  [USER].parentid = corp.corp_id and [USER].parentid=@Myparentid
go


create procedure dbo.Expo_GetUserInfo_UserID @userid nvarchar(50) as
declare @Myuserid nvarchar(50)
    
    set @userid=replace(@userid,'''','''''') 
    set @userid=replace(@userid,'--','') 
    set @userid=replace(@userid,';','') 
set @Myuserid =@userid


SELECT [USER].*, Corp.corp_name, Corp.corp_name_e, corp.defaultrate, corp.IATA,corp.fax,corp.sendfax, corp.credit,corp.HotelGroupID,corp.corp_ID FROM [USER],[Corp] where  [USER].parentid = corp.corp_id and [USER].userid=@Myuserid
go


create procedure dbo.Expo_Hotel_CheckRate_H_cache @Property_id int,
 @plancode varchar(50),
 @Chickindate datetime,
 @Chickoutdate datetime as
select plancode as xmlallotment,plancode as xmlpricenotax, [ID],property_id,plancode,convert(nvarchar(10),AvailDate,120) AS AvailDate,gua,cxl,singlerate,doublerate,triplerate,quadrate,extraadult,extrachildren,allotment,allotmax,avstat,maxlos,minlos,ratecode,roomcode,tcode,t_from,t_to,roomdesc,ratedesc,gua,cxl,pricenotax,cutoff from h_cache where Property_id=@Property_id and Availdate>=@Chickindate and Availdate<@Chickoutdate and plancode=@plancode order by Availdate
go


create procedure dbo.Expo_ResvLog_Add @userid int,
 @usertype nvarchar(50),
 @propertyid int,
 @roomtype nvarchar(50),
 @rateclass nvarchar(50),
 @starttime datetime,
 @deptime datetime,
 @updatetime datetime,
 @nights int,
 @room int,
 @guestfirstname nvarchar(50),
 @guestlastname nvarchar(50),
 @guestemail nvarchar(50),
 @guestphone nvarchar(50),
 @guestMP nvarchar(50),
 @guestaddressline1 nvarchar(50),
 @guestaddressline2 nvarchar(50),
 @guestcity nvarchar(50),
 @guestcountry nvarchar(50),
 @gueststate nvarchar(50),
 @guestzip nvarchar(50),
 @cctype nvarchar(50),
 @ccnumber nvarchar(50),
 @ccname nvarchar(50),
 @ccexpyear nvarchar(50),
 @ccexpmonth nvarchar(50),
 @frequentguestid nvarchar(50),
 @iata nvarchar(50),
 @remarks ntext,
 @confnum nvarchar(50),
 @cxlnum nvarchar(50),
 @status nvarchar(50),
 @propertyname nvarchar(500),
 @propertyname_e nvarchar(500),
 @totalmount nvarchar(50),
 @dailyprice varchar(2000),
 @adults int,
 @children int,
 @plandesc varchar(500),
 @roomname varchar(500),
 @roomdesc varchar(500),
 @canclerule nvarchar(500),
 @guaranteerule nvarchar(500),
 @taxrule nvarchar(500),
 @incomingcall nvarchar(50),
 @fromurl nvarchar(255),
 @deleted int,
 @SubSource nvarchar(50),
 @lastuser nvarchar(50),
 @lastusertype nvarchar(50),
 @verifycode nvarchar(50),
 @getstatus int,
 @flgorder int,
 @departure datetime,
 @payment nvarchar(50),
 @outconfnum nvarchar(50) as
insert into
 resvlog(userid,usertype,propertyid,roomtype,rateclass,starttime,deptime,updatetime,nights,room,guestfirstname,guestlastname,guestemail,guestphone,guestMP,guestaddressline1,guestaddressline2,guestcity,guestcountry,gueststate,guestzip,cctype,ccnumber,ccname,ccexpyear,ccexpmonth,frequentguestid,iata,remarks,confnum,cxlnum,status,propertyname,propertyname_e,totalmount,dailyprice,adults,children,plandesc,roomname,roomdesc,canclerule,guaranteerule,taxRule,incomingcall,fromurl,deleted,SubSource,lastuser,lastuser
type,verifycode,getstatus,flgorder,departure,payment,outconfnum)
 values(@userid,@usertype,@propertyid,@roomtype,@rateclass,@starttime,@deptime,@updatetime,@nights,@room,@guestfirstname,@guestlastname,@guestemail,@guestphone,@guestMP,@guestaddressline1,@guestaddressline2,@guestcity,@guestcountry,@gueststate,@guestzip,@cctype,@ccnumber,@ccname,@ccexpyear,@ccexpmonth,@frequentguestid,@iata,@remarks,@confnum,@cxlnum,@status,@propertyname,@propertyname_e,@totalmount,@dailyprice,@adults,@children,@plandesc,@roomname,@roomdesc,@canclerule,@guaranteerule,@taxrule,@incomingcall
,@fromurl,@deleted,@SubSource,@lastuser,@lastusertype,@verifycode,@getstatus,@flgorder,@departure,@payment,@outconfnum)
go


create procedure dbo.Expo_ResvLog_Add_Special @userid int,
 @usertype nvarchar(50),
 @propertyid int,
 @roomtype nvarchar(50),
 @rateclass nvarchar(50),
 @starttime datetime,
 @deptime datetime,
 @updatetime datetime,
 @nights int,
 @room int,
 @guestfirstname nvarchar(50),
 @guestlastname nvarchar(50),
 @guestemail nvarchar(50),
 @guestphone nvarchar(50),
 @guestMP nvarchar(50),
 @guestaddressline1 nvarchar(50),
 @guestaddressline2 nvarchar(50),
 @guestcity nvarchar(50),
 @guestcountry nvarchar(50),
 @gueststate nvarchar(50),
 @guestzip nvarchar(50),
 @cctype nvarchar(50),
 @ccnumber nvarchar(50),
 @ccname nvarchar(50),
 @ccexpyear nvarchar(50),
 @ccexpmonth nvarchar(50),
 @frequentguestid nvarchar(50),
 @iata nvarchar(50),
 @remarks ntext,
 @confnum nvarchar(50),
 @cxlnum nvarchar(50),
 @status nvarchar(50),
 @propertyname nvarchar(500),
 @propertyname_e nvarchar(500),
 @totalmount nvarchar(50),
 @dailyprice varchar(2000),
 @adults int,
 @children int,
 @plandesc varchar(500),
 @roomname varchar(500),
 @roomdesc varchar(500),
 @canclerule nvarchar(500),
 @guaranteerule nvarchar(500),
 @taxrule nvarchar(500),
 @incomingcall nvarchar(50),
 @fromurl nvarchar(255),
 @deleted int,
 @SubSource nvarchar(50),
 @lastuser nvarchar(50),
 @lastusertype nvarchar(50),
 @verifycode nvarchar(50),
 @getstatus int,
 @flgorder int,
 @departure datetime,
 @payment nvarchar(50),
 @outconfnum nvarchar(50),
 @expotype int as
insert into
 expo_resvlog(userid,usertype,propertyid,roomtype,rateclass,starttime,deptime,updatetime,nights,room,guestfirstname,guestlastname,guestemail,guestphone,guestMP,guestaddressline1,guestaddressline2,guestcity,guestcountry,gueststate,guestzip,cctype,ccnumber,ccname,ccexpyear,ccexpmonth,frequentguestid,iata,remarks,confnum,cxlnum,status,propertyname,propertyname_e,totalmount,dailyprice,adults,children,plandesc,roomname,roomdesc,canclerule,guaranteerule,taxRule,incomingcall,fromurl,deleted,SubSource,lastuser,las
tusertype,verifycode,getstatus,flgorder,departure,payment,outconfnum,expotype)
 values(@userid,@usertype,@propertyid,@roomtype,@rateclass,@starttime,@deptime,@updatetime,@nights,@room,@guestfirstname,@guestlastname,@guestemail,@guestphone,@guestMP,@guestaddressline1,@guestaddressline2,@guestcity,@guestcountry,@gueststate,@guestzip,@cctype,@ccnumber,@ccname,@ccexpyear,@ccexpmonth,@frequentguestid,@iata,@remarks,@confnum,@cxlnum,@status,@propertyname,@propertyname_e,@totalmount,@dailyprice,@adults,@children,@plandesc,@roomname,@roomdesc,@canclerule,@guaranteerule,@taxrule,@incomingcall
,@fromurl,@deleted,@SubSource,@lastuser,@lastusertype,@verifycode,@getstatus,@flgorder,@departure,@payment,@outconfnum,@expotype)
go


create procedure dbo.Expo_ResvLog_Addstat @userid int,
 @usertype nvarchar(50),
 @propertyid int,
 @roomtype nvarchar(50),
 @rateclass nvarchar(50),
 @starttime datetime,
 @deptime datetime,
 @updatetime datetime,
 @nights int,
 @room int,
 @guestfirstname nvarchar(50),
 @guestlastname nvarchar(50),
 @guestemail nvarchar(50),
 @guestphone nvarchar(50),
 @guestaddressline1 nvarchar(50),
 @guestaddressline2 nvarchar(50),
 @guestcity nvarchar(50),
 @guestcountry nvarchar(50),
 @gueststate nvarchar(50),
 @guestzip nvarchar(50),
 @cctype nvarchar(50),
 @ccnumber nvarchar(50),
 @ccname nvarchar(50),
 @ccexpyear nvarchar(50),
 @ccexpmonth nvarchar(50),
 @frequentguestid nvarchar(50),
 @iata nvarchar(50),
 @remarks ntext,
 @confnum nvarchar(50),
 @cxlnum nvarchar(50),
 @status nvarchar(50),
 @propertyname nvarchar(500),
 @propertyname_e nvarchar(500),
 @totalmount nvarchar(50),
 @totalrevenue decimal(18,2),
 @dailyprice varchar(2000),
 @adults int,
 @children int,
 @plandesc varchar(500),
 @roomname varchar(500),
 @roomdesc varchar(500),
 @canclerule nvarchar(500),
 @guaranteerule nvarchar(500),
 @incomingcall nvarchar(50),
 @fromurl nvarchar(255),
 @deleted int,
 @SubSource nvarchar(50),
 @lastuser nvarchar(50),
 @lastusertype nvarchar(50),
 @verifycode nvarchar(50),
 @getstatus int,
 @flgorder int,
 @departure datetime,
 @pmsno nvarchar(50),
 @roomno nvarchar(50) as
insert into
 resvlog(userid,usertype,propertyid,roomtype,rateclass,starttime,deptime,updatetime,nights,room,guestfirstname,guestlastname,guestemail,guestphone,guestaddressline1,guestaddressline2,guestcity,guestcountry,gueststate,guestzip,cctype,ccnumber,ccname,ccexpyear,ccexpmonth,frequentguestid,iata,remarks,confnum,cxlnum,status,propertyname,propertyname_e,totalmount,totalrevenue,dailyprice,adults,children,plandesc,roomname,roomdesc,canclerule,guaranteerule,incomingcall,fromurl,deleted,SubSource,lastuser,lastusertyp
e,verifycode,getstatus,flgorder,departure,pmsno,roomno)
 values(@userid,@usertype,@propertyid,@roomtype,@rateclass,@starttime,@deptime,@updatetime,@nights,@room,@guestfirstname,@guestlastname,@guestemail,@guestphone,@guestaddressline1,@guestaddressline2,@guestcity,@guestcountry,@gueststate,@guestzip,@cctype,@ccnumber,@ccname,@ccexpyear,@ccexpmonth,@frequentguestid,@iata,@remarks,@confnum,@cxlnum,@status,@propertyname,@propertyname_e,@totalmount,@totalrevenue,@dailyprice,@adults,@children,@plandesc,@roomname,@roomdesc,@canclerule,@guaranteerule,@incomingcall,@fr
omurl,@deleted,@SubSource,@lastuser,@lastusertype,@verifycode,@getstatus,@flgorder,@departure,@pmsno,@roomno)
go


create procedure dbo.Expo_ResvLog_Mod @userid int,
 @usertype nvarchar(50),
 @propertyid int,
 @roomtype nvarchar(50),
 @rateclass nvarchar(50),
 @starttime datetime,
 @deptime datetime,
 @updatetime datetime,
 @nights int,
 @room int,
 @guestfirstname nvarchar(50),
 @guestlastname nvarchar(50),
 @guestemail nvarchar(50),
 @guestphone nvarchar(50),
 @guestMP nvarchar(50),
 @guestaddressline1 nvarchar(50),
 @guestaddressline2 nvarchar(50),
 @guestcity nvarchar(50),
 @guestcountry nvarchar(50),
 @gueststate nvarchar(50),
 @guestzip nvarchar(50),
 @cctype nvarchar(50),
 @ccnumber nvarchar(50),
 @ccname nvarchar(50),
 @ccexpyear nvarchar(50),
 @ccexpmonth nvarchar(50),
 @frequentguestid nvarchar(50),
 @iata nvarchar(50),
 @remarks ntext,
 @cxlnum nvarchar(50),
 @status nvarchar(50),
 @propertyname nvarchar(500),
 @propertyname_e nvarchar(500),
 @totalmount nvarchar(50),
 @dailyprice varchar(2000),
 @adults int,
 @children int,
 @plandesc varchar(500),
 @roomname varchar(500),
 @roomdesc varchar(500),
 @canclerule nvarchar(500),
 @guaranteerule nvarchar(500),
 @taxrule nvarchar(500),
 @incomingcall nvarchar(50),
 @fromurl nvarchar(255),
 @deleted int,
 @SubSource nvarchar(50),
 @lastuser nvarchar(50),
 @lastusertype nvarchar(50),
 @verifycode nvarchar(50),
 @outconfnum nvarchar(50) as
update resvlog set 
 userid=@userid,usertype=@usertype,propertyid=@propertyid,roomtype=@roomtype,rateclass=@rateclass,starttime=@starttime,deptime=@deptime,updatetime=@updatetime,nights=@nights,room=@room,guestfirstname=@guestfirstname,guestlastname=@guestlastname,guestemail=@guestemail,guestphone=@guestphone,guestMP=@guestMP,guestaddressline1=@guestaddressline1,guestaddressline2=@guestaddressline2,guestcity=@guestcity,guestcountry=@guestcountry,gueststate=@gueststate,guestzip=@guestzip,cctype=@cctype,ccnumber=@ccnumber,ccnam
e=@ccname,ccexpyear=@ccexpyear,ccexpmonth=@ccexpmonth,frequentguestid=@frequentguestid,iata=@iata,remarks=@remarks,cxlnum=@cxlnum,status=@status,propertyname=@propertyname,propertyname_e=@propertyname_e,totalmount=@totalmount,dailyprice=@dailyprice,adults=@adults,children=@children,plandesc=@plandesc,roomname=@roomname,roomdesc=@roomdesc,canclerule=@canclerule,guaranteerule=@guaranteerule,taxRule=@taxrule,incomingcall=@incomingcall,fromurl=@fromurl,deleted=@deleted,SubSource=@SubSource,lastuser=@lastuser,l
astusertype=@lastusertype,verifycode=@verifycode,outconfnum=@outconfnum where propertyid=@propertyid and verifycode=@verifycode
go


create procedure dbo.Expo_ResvLog_Sel @verifycode nvarchar(50) as
select * from  resvlog where  verifycode=@verifycode
go


create procedure dbo.Expo_Resvlog_UpdatePmsRoom @pmsno nvarchar(100),
 @roomno nvarchar(100),
 @confnum nvarchar(50) as
update resvlog 
set
pmsno=@pmsno,roomno=@roomno
where confnum=@confnum
go


create procedure dbo.Expo_SearchDFBHotel @Title nvarchar(50),
 @City int,
 @District int,
 @Commercial int,
 @CheckIn datetime,
 @CheckOut datetime,
 @PriceRange nvarchar(50),
 @AirPortDistance int,
 @Stars int,
 @hotelGeography nvarchar(2000),
 @AirPortCode nvarchar(50),
 @ConfirmationType nvarchar(50),
 @Plan nvarchar(500), 
 @GroupID nvarchar(2000), 
 @PageSize int=10, 
 @CurPage int=1, 
 @doCount int, 
 @languagetype int as
declare @MyTitle nvarchar(50)
    
    set @Title=replace(@Title,'''','''''') 
    set @Title=replace(@Title,'--','') 
    set @Title=replace(@Title,';','') 
set @MyTitle = '%'+@Title+'%'


    
   
   
    



declare @s varchar(6000) 
declare @stemp varchar(6000) 
if (@doCount != 0)  
begin 
set @s ='select count(*) as Total from dbo.Hotel '
end
else
begin
declare @PageIndex int
set @PageIndex=@CurPage*@PageSize
set @s ='select  top ' + cast(@PageSize as nvarchar(20)) + ' * from (select top ' + cast(@PageSize as nvarchar(20)) + ' * from (select top ' +cast(@PageIndex as nvarchar(20)) + ' * from dbo.Hotel '
end

if (@GroupID != '')  
begin 
if (@languagetype=0)
begin
set @s =@s+' where passed=1 and  '+@GroupID
end
else
begin
set @s =@s+' where enpassed=1 and  '+@GroupID
end
end
else
begin
if (@languagetype=0)
begin
set @s =@s+' where passed=1 '
end
else
begin
set @s =@s+' where enpassed=1 '
end
end

set @stemp =''


if (@Title!='')
set @stemp =@stemp+'and (Title like '''+@MyTitle+''' or Title_e like '''+@MyTitle+''' or keywords like ''%'+@MyTitle+'%'' )'

if (@Stars!=10)
begin
if(@Stars=0)
set @stemp =@stemp+' and (Stars =0 and Diamond=0)'
else
set @stemp =@stemp+' and (Stars ='+ cast(@Stars as varchar)+' or Diamond='+ cast(@Stars as varchar)+')'
end

if (@hotelGeography!='')
set @stemp =@stemp+' and (address1 like''%'+@hotelGeography+'%'' or address1_e like ''%'+@hotelGeography+'%'' or pid in (select pid from h_baseinfo where address1 like ''%'+@hotelGeography+'%''))'

	


	
	
	

if (@City!=-1)
set @stemp=@stemp+' and cityid='+ cast(@City as varchar)

if (@District!=-1)
set @stemp=@stemp+' and districtid='+ cast(@District as varchar)

if (@Commercial!=-1)
set @stemp=@stemp+' and commercialid='+ cast(@Commercial as varchar)



set @stemp =@stemp+ ' and (pid in(select distinct property_id from h_cache where '
if (@Plan!='')
	begin
	set @stemp =@stemp+@Plan+ '  and  '
	end
if (@PriceRange!='')
begin
	declare @MyPriceRange nvarchar(100)

	if (@PriceRange='<=250')
	set @MyPriceRange ='priceNoTax>0 and priceNoTax<= 250'
	if (@PriceRange='250-400')
	set @MyPriceRange ='priceNoTax>250 and priceNoTax<=400'
	if (@PriceRange='400-600')
	set @MyPriceRange ='priceNoTax>400 and priceNoTax<=600'
	if (@PriceRange='600-800')
	set @MyPriceRange ='priceNoTax>600 and priceNoTax<=800'
	if (@PriceRange='>800')
	set @MyPriceRange ='priceNoTax> 800'

	set @stemp =@stemp +@MyPriceRange+' '
	
end
else
begin
set @stemp =@stemp+ '  priceNoTax>0 and allotment>0 '
end

set @stemp =@stemp+ '  and avstat!=''N''  and (datediff(hh,getdate(),Availdate)+24>=cutoff)  and  Availdate>= '''+convert(varchar(10),@CheckIn,120)+''' AND Availdate<'''+convert(varchar(10),@CheckOut,120)+''') )'




if (@doCount =0)
begin
set @s =@s+@stemp+ ' order by credit desc, pagerank desc,hotel_id ) as aa  order by credit,pagerank ,hotel_id desc) as aa order by credit desc,pagerank desc,hotel_id'
end
else
set @s =@s+@stemp

exec ( @s )
print @s
go


create procedure dbo.Expo_SearchHotel @Title nvarchar(50),
 @City int,
 @District int,
 @Commercial int,
 @CheckIn datetime,
 @CheckOut datetime,
 @PriceRange nvarchar(50),
 @AirPortDistance int,
 @Stars int,
 @hotelGeography nvarchar(2000),
 @AirPortCode nvarchar(50),
 @ConfirmationType nvarchar(50),
 @Plan nvarchar(500), 
 @GroupID nvarchar(2000), 
 @PageSize int=10, 
 @CurPage int=1, 
 @doCount int, 
 @languagetype int as
declare @MyTitle nvarchar(50)
    
    set @Title=replace(@Title,'''','''''') 
    set @Title=replace(@Title,'--','') 
    set @Title=replace(@Title,';','') 
set @MyTitle = '%'+@Title+'%'


    
   
   
    



declare @s varchar(6000) 
declare @stemp varchar(6000) 



if (@doCount != 0)  
begin 
set @s ='select count(*) as Total from dbo.Hotel '
end
else
begin
declare @PageIndex int
set @PageIndex=@CurPage*@PageSize

set @s ='select  top ' + cast(@PageSize as nvarchar(20)) + ' * from (select top ' + cast(@PageSize as nvarchar(20)) + ' * from (select top ' +cast(@PageIndex as nvarchar(20)) + ' * from dbo.Hotel '
end

if (@GroupID != '')  
begin 
if (@languagetype=0)
begin
set @s =@s+' where pid in (select distinct property_id from expo_cache where allotment>0) and  passed=1 and  '+@GroupID
end
else
begin
set @s =@s+' where pid in (select distinct property_id from expo_cache where allotment>0) and enpassed=1 and  '+@GroupID
end
end
else
begin
if (@languagetype=0)
begin
set @s =@s+' where pid in (select distinct property_id from expo_cache where allotment>0) and passed=1 '
end
else
begin
set @s =@s+' where pid in (select distinct property_id from expo_cache where allotment>0) and enpassed=1 '
end
end

set @stemp =''


if (@Title!='')
set @stemp =@stemp+'and (Title like '''+@MyTitle+''' or Title_e like '''+@MyTitle+''' or keywords like ''%'+@MyTitle+'%'' )'

if (@Stars!=10)
begin
if(@Stars=0)
set @stemp =@stemp+' and (Stars =0 and Diamond=0)'
else
set @stemp =@stemp+' and (Stars ='+ cast(@Stars as varchar)+' or Diamond='+ cast(@Stars as varchar)+')'
end

if (@hotelGeography!='')
set @stemp =@stemp+' and (address1 like''%'+@hotelGeography+'%'' or address1_e like ''%'+@hotelGeography+'%'' or pid in (select pid from h_baseinfo where address1 like ''%'+@hotelGeography+'%''))'

	


	
	
	

if (@City!=-1)
set @stemp=@stemp+' and cityid='+ cast(@City as varchar)

if (@District!=-1)
set @stemp=@stemp+' and districtid='+ cast(@District as varchar)

if (@Commercial!=-1)
set @stemp=@stemp+' and commercialid='+ cast(@Commercial as varchar)



set @stemp =@stemp+ ' and (pid in(select distinct property_id from expo_cache where '
if (@Plan!='')
	begin
	set @stemp =@stemp+@Plan+ '  and  '
	end
if (@PriceRange!='')
begin
	declare @MyPriceRange nvarchar(100)

	if (@PriceRange='<=250')
	set @MyPriceRange ='priceNoTax>0 and priceNoTax<= 250'
	if (@PriceRange='250-400')
	set @MyPriceRange ='priceNoTax>250 and priceNoTax<=400'
	if (@PriceRange='400-600')
	set @MyPriceRange ='priceNoTax>400 and priceNoTax<=600'
	if (@PriceRange='600-800')
	set @MyPriceRange ='priceNoTax>600 and priceNoTax<=800'
	if (@PriceRange='>800')
	set @MyPriceRange ='priceNoTax> 800'

	set @stemp =@stemp +@MyPriceRange+' '
	
end
else
begin
set @stemp =@stemp+ '  priceNoTax>0 '
end

set @stemp =@stemp+ '  and avstat!=''N''  and (datediff(hh,getdate(),Availdate)+24>=cutoff)  and  Availdate>= '''+convert(varchar(10),@CheckIn,120)+''' AND Availdate<'''+convert(varchar(10),@CheckOut,120)+''') )'




if (@doCount =0)
begin
set @s =@s+@stemp+ ' order by credit desc, pagerank desc,hotel_id ) as aa  order by credit,pagerank ,hotel_id desc) as aa order by credit desc,pagerank desc,hotel_id'
end
else
set @s =@s+@stemp
print @s
exec ( @s )
print @s
go


create procedure dbo.Expo_SearchMonthPriceHotel @Title nvarchar(50),
 @City int,
 @District int,
 @Commercial int,
 @CheckIn datetime,
 @CheckOut datetime,
 @PriceRange nvarchar(50),
 @AirPortDistance int,
 @Stars int,
 @hotelGeography nvarchar(2000),
 @AirPortCode nvarchar(50),
 @ConfirmationType nvarchar(50),
 @Plan nvarchar(500), 
 @GroupID nvarchar(2000), 
 @PageSize int=10, 
 @CurPage int=1, 
 @doCount int, 
 @languagetype int as
declare @MyTitle nvarchar(50)
    
    set @Title=replace(@Title,'''','''''') 
    set @Title=replace(@Title,'--','') 
    set @Title=replace(@Title,';','') 
set @MyTitle = '%'+@Title+'%'


    
   
   
    



declare @s varchar(6000) 
declare @stemp varchar(6000) 



if (@doCount != 0)  
begin 
set @s ='select count(*) as Total from dbo.Hotel '
end
else
begin
declare @PageIndex int
set @PageIndex=@CurPage*@PageSize

set @s ='select  top ' + cast(@PageSize as nvarchar(20)) + ' * from (select top ' + cast(@PageSize as nvarchar(20)) + ' * from (select top ' +cast(@PageIndex as nvarchar(20)) + ' * from dbo.Hotel '
end

if (@GroupID != '')  
begin 
if (@languagetype=0)
begin
set @s =@s+' where pid in (select distinct property_id from expo_cache where allotment>0) and  passed=1 and  '+@GroupID
end
else
begin
set @s =@s+' where pid in (select distinct property_id from expo_cache where allotment>0) and enpassed=1 and  '+@GroupID
end
end
else
begin
if (@languagetype=0)
begin
set @s =@s+' where pid in (select distinct property_id from expo_cache where allotment>0) and passed=1 '
end
else
begin
set @s =@s+' where pid in (select distinct property_id from expo_cache where allotment>0) and enpassed=1 '
end
end


set @stemp =''


if (@Title!='')
set @stemp =@stemp+'and (Title like '''+@MyTitle+''' or Title_e like '''+@MyTitle+''' or keywords like ''%'+@MyTitle+'%'' )'

if (@Stars!=10)
begin
if(@Stars=0)
set @stemp =@stemp+' and (Stars =0 and Diamond=0)'
else
set @stemp =@stemp+' and (Stars ='+ cast(@Stars as varchar)+' or Diamond='+ cast(@Stars as varchar)+')'
end

if (@hotelGeography!='')
set @stemp =@stemp+' and (address1 like''%'+@hotelGeography+'%'' or address1_e like ''%'+@hotelGeography+'%'' or pid in (select pid from h_baseinfo where address1 like ''%'+@hotelGeography+'%''))'

	


	
	
	

if (@City!=-1)
set @stemp=@stemp+' and cityid='+ cast(@City as varchar)

if (@District!=-1)
set @stemp=@stemp+' and districtid='+ cast(@District as varchar)

if (@Commercial!=-1)
set @stemp=@stemp+' and commercialid='+ cast(@Commercial as varchar)











--










--








declare @CheckInTime varchar(20)
declare @CheckOutTime Varchar(20)

select @CheckInTime = convert(nvarchar,year(@CheckIn))+'-'+Convert(nvarchar,month(@CheckIn))+'-1'
select @CheckOutTime = convert(nvarchar,year(@CheckOut))+'-'+Convert(nvarchar,month(@CheckOut))+'-1'

set @stemp = @stemp+ 'and (pid in(select distinct property_id from expo_cache where priceNoTax>0 and '+@Plan+' and (datediff(hh,getdate(),Availdate)+24>=cutoff) and Availdate >= '''+@CheckInTime+''' and Availdate <='''+@CheckOutTime+''' ))'





print @stemp

if (@doCount =0)
begin
set @s =@s+@stemp+ ' order by credit desc, pagerank desc,hotel_id ) as aa  order by credit,pagerank ,hotel_id desc) as aa order by credit desc,pagerank desc,hotel_id'
end
else
set @s =@s+@stemp
print @s
exec ( @s )
print @s
go


create procedure dbo.Expo_Searchapply ( 
         @tablename varchar(100),
         @fieldlist varchar(4000)='*',
         @orderfield varchar(100),
         @keyfield varchar(100),
         @pageindex int,
         @pagesize int=20,
         @strwhere varchar(4000)= null ,
         @ordertype bit=1
 	
     ) as
SET NOCOUNT ON 
    declare @sqlstr varchar(6000) 
    Declare @sql nvarchar(4000);
    declare @totalRecord int;
    
    set @strwhere=replace(@strwhere,'''','''''') 
    set @strwhere=replace(@strwhere,'--','') 
    set @strwhere=replace(@strwhere,';','') 
       
  
       
   
     
        

    
    
    set @sqlstr='declare @CurPageNum int;' 
    set @sqlstr=@sqlstr+'declare @nextpagenum int;' 
    set @sqlstr=@sqlstr+'set @curpagenum='+cast(@PageIndex as varchar)+'*'+cast(@Pagesize as varchar)+';' 
    set @sqlstr=@sqlstr+'set @nextpagenum='+cast(@PageIndex+1 as varchar)+'*'+cast(@Pagesize as varchar)+';' 
    set @sqlstr=@sqlstr+'declare @sqlstr varchar(6000);' 
    if @ordertype=1 
    begin 
    set @sqlstr=@sqlstr+'set @sqlstr=''select '+@fieldlist+' from ( select top ''+cast(@nextpagenum as varchar)+'' * from  
 
'+@tablename+'  where  '+@strwhere+' order by '+@orderfield+' desc ) as a where '+@keyfield+' not in (  
 
select top ''+cast(@curpagenum as varchar)+'' '+@keyfield+' from '+@tablename+' where '+@strwhere+'  
 
order by '+@orderfield+' desc) order by '+@orderfield+' desc'';' 
    end 
    else 
    begin 
    set @sqlstr=@sqlstr+'set @sqlstr=''select '+@fieldlist+' from ( select top ''+cast(@nextpagenum as varchar)+'' * from  
 
'+@tablename+'  where '+@strwhere+' order by '+@orderfield+' asc ) as a where '+@keyfield+' not in (  
 
select top ''+cast(@curpagenum as varchar)+'' '+@keyfield+' from '+@tablename+' where '+@strwhere+'  
 
order by '+@orderfield+' asc) order by '+@orderfield+' asc'';' 
    end 
     
    set @sqlstr=@sqlstr+'execute( @sqlstr)' 
    execute(@sqlstr)
    
go


create procedure dbo.Expo_SelectCXL @Property_id int,
 @Languagetype int,
 @Rule nvarchar(50) as
select * from H_cxlrule where Property_id=@Property_id and [Rule]=@Rule and languagetype=@Languagetype
go


create procedure dbo.Expo_SelectGUA @Property_id int,
 @Languagetype int,
 @Grule nvarchar(50) as
select * from H_guarule where property_id=@Property_id and Grule=@Grule and languagetype=@Languagetype
go


create procedure dbo.Expo_SelectHotel (
 	@Hotel_ID int
 	) as
select * from hotel where Hotel_ID=@Hotel_ID
go


create procedure dbo.Expo_SelectTAX (
 	@Property_id int,
 	@languagetype int
 	) as
select * from H_tax where property_id=@Property_id and languagetype=@languagetype
go


create procedure dbo.Expo_Sendsms @orig_mobile nvarchar(50),
 @content nvarchar(160) as
insert into sms_send(orig_mobile,content) values(@orig_mobile,@content)
go


create procedure dbo.Expo_UpdateLog @username nvarchar(100),
 @verifycode nvarchar(100),
 @typecode int,
 @typename nvarchar(200),
 @updatetime varchar(50),
 @userip varchar(50),
 @upcontent ntext as
insert into update_log(username,verifycode,typecode,typename,updatetime,userip,upcontent)
values(@username,@verifycode,@typecode,@typename,@updatetime,@userip,@upcontent)
go


create procedure dbo.Expo_UpdateResvLog @Confnum nvarchar(50),
 @Getstatus int,
 @Totalrevenue decimal,
 @Departure datetime,
 @status nvarchar(50) as
update dbo.Resvlog  set Getstatus=@Getstatus,Totalrevenue=@Totalrevenue,Departure=@Departure where confnum=@Confnum
go


create procedure dbo.Expo_User_Add @username nvarchar(50),
 
 @UserPassword nvarchar(50),
 
 @Email nvarchar(255),
 
 @address nvarchar(255),
 
 @tel nvarchar(50),
 
 @firstname nvarchar(50),
 
 @lastname nvarchar(50),
 
 @parentid int,
 
 @remark varchar(500),
 
 @userlevel int,
 
 @booktimes int,
 
 @totalmount decimal(19,2),
 
 @roomnights int,
 
 @usertype nvarchar(50),
 
 @congeal int as
set @userlevel=@userlevel

insert into [user](username,UserPassword,Email,address,tel,firstname,lastname,parentid,remark,userlevel,booktimes,totalmount,roomnights,usertype,congeal)

values(@username,@UserPassword,@Email,@address,@tel,@firstname,@lastname,@parentid,@remark,@userlevel,@booktimes,@totalmount,@roomnights,@usertype,@congeal)
go


create procedure dbo.Exptia_GetResvAll_byName @Confnum nvarchar(50),@LastName as
nvarchar(50)
as
declare @MyConfnum nvarchar(50)
    set @Confnum=replace(@Confnum,'''','''''') 
    set @Confnum=replace(@Confnum,'--','') 
    set @Confnum=replace(@Confnum,';','')
    set @LastName=replace(@LastName,'''','''''') 
    set @LastName=replace(@LastName,'--','') 
    set @LastName=replace(@LastName,';','')
set @MyConfnum =@Confnum
SELECT resvlog.*,hotel.phone,hotel.address1,hotel.address1_e,hotel.checkin,hotel.checkout FROM [resvlog],[hotel] where  guestlastname=@LastName and confnum=@MyConfnum   and(resvlog.propertyid=hotel.pid or resvlog.propertyid=hotel.pid_e)
go


create procedure dbo.FGB_GetEmailIsValidateCode @gid as
int ,@uid as int,@checkcode as varchar(50),@hours as int
as 
if @hours<0
set @hours=10;
select @uid=uid from hweb_user where   getdate()<DATEADD(hh,@hours,Checkcodedate) and usercheckcode = @checkcode and uid =@uid and  gid=@gid
 if(@@rowcount>0)
   begin
               update hweb_user set emailcheck=1,Checkcodedate=getdate(),usercheckcode='' where uid=@uid;
               select 1 as pass;   
   end 
  else
      begin
                select 0 as pass   
      end
go


create procedure dbo.FGB_GetResvAll @Confnum nvarchar(50),@uid as
int
as
declare @MyConfnum nvarchar(50)
    
    set @Confnum=replace(@Confnum,'''','''''') 
    set @Confnum=replace(@Confnum,'--','') 
    set @Confnum=replace(@Confnum,';','')
set @MyConfnum =@Confnum

SELECT resvlog.*,hotel.phone,hotel.address1,hotel.address1_e,hotel.checkin,hotel.checkout FROM [resvlog],[hotel] where    confnum=@MyConfnum and (resvlog.propertyid=hotel.pid or resvlog.propertyid=hotel.pid_e)
and verifycode in(select top 1  verifycode from  hweb_scorelog where uid=@uid  and fogid=@Confnum)
go


create procedure dbo.FGB_GetUserIsValidateCode @gid as
int ,@username as varchar(50),@checkcode as varchar(50), @type as varchar(1),@hours as int
as 
declare @uid as int
if @hours<0
set @hours=10;
select @uid=uid from hweb_user where
  getdate()<DATEADD(hh,@hours,Checkcodedate)
and usercheckcode = @checkcode and uid in (select uid from  hweb_user_username  where username = @username and  gid=@gid )
 if(@uid>0)
          begin
                 if(@type='e')
                  begin
                      update hweb_user set emailcheck=1,Checkcodedate=getdate(),usercheckcode='' where uid=@uid;
                  end
                  else
                   begin
                      update hweb_user set emailcheck=1,Checkcodedate=getdate() where uid=@uid;  
                   end
                  select 1 as pass   
          end 
  else
          begin
                   select 0 as pass   
          end
go


create procedure dbo.FGB_JJ_GetPagingRecord ( 
         @tablename varchar(100),
         @fieldlist varchar(4000)='*',
         @orderfield varchar(100),
         @keyfield varchar(100),
         @pageindex int,
         @pagesize int=20,
         @strwhere varchar(4000)= null ,
         @ordertype bit=1
 	
     ) as
SET NOCOUNT ON 
    declare @sqlstr varchar(6000) 
    Declare @sql nvarchar(4000);
    declare @totalRecord int;
    
    set @strwhere=replace(@strwhere,'''','''''') 
    set @strwhere=replace(@strwhere,'--','') 
    set @strwhere=replace(@strwhere,';','') 
       
  
       
   
     
        

    
    
    set @sqlstr='declare @CurPageNum int;' 
    set @sqlstr=@sqlstr+'declare @nextpagenum int;' 
    set @sqlstr=@sqlstr+'set @curpagenum='+cast(@PageIndex as varchar)+'*'+cast(@Pagesize as varchar)+';' 
    set @sqlstr=@sqlstr+'set @nextpagenum='+cast(@PageIndex+1 as varchar)+'*'+cast(@Pagesize as varchar)+';' 
    set @sqlstr=@sqlstr+'declare @sqlstr varchar(6000);' 
    if @ordertype=1 
    begin 
    set @sqlstr=@sqlstr+'set @sqlstr=''select '+@fieldlist+' from ( select top ''+cast(@nextpagenum as varchar)+'' * from  
 
'+@tablename+'  where  '+@strwhere+' order by '+@orderfield+' desc ) as a where '+@keyfield+' not in (  
 
select top ''+cast(@curpagenum as varchar)+'' '+@keyfield+' from '+@tablename+' where '+@strwhere+'  
 
order by '+@orderfield+' desc) order by '+@orderfield+' desc'';' 
    end 
    else 
    begin 
    set @sqlstr=@sqlstr+'set @sqlstr=''select '+@fieldlist+' from ( select top ''+cast(@nextpagenum as varchar)+'' * from  
 
'+@tablename+'  where '+@strwhere+' order by '+@orderfield+' asc ) as a where '+@keyfield+' not in (  
 
select top ''+cast(@curpagenum as varchar)+'' '+@keyfield+' from '+@tablename+' where '+@strwhere+'  
 
order by '+@orderfield+' asc) order by '+@orderfield+' asc'';' 
    end 
     
    set @sqlstr=@sqlstr+'execute( @sqlstr)' 
    execute(@sqlstr)
    
go


create procedure dbo.FGB_JJ_GetResv @Confnum nvarchar(50) as
declare @MyConfnum nvarchar(50)
    
    set @Confnum=replace(@Confnum,'''','''''') 
    set @Confnum=replace(@Confnum,'--','') 
    set @Confnum=replace(@Confnum,';','') 
set @MyConfnum =@Confnum


SELECT * FROM [resvlog] where  confnum=@MyConfnum
go


create procedure dbo.FGB_JJ_GetResvAll @Confnum nvarchar(50),@LastName as
nvarchar(50),@cardnumber as nvarchar(100)
as
  if @LastName=''
        begin
        SELECT resvlog.*,hotel.phone,hotel.address1,hotel.address1_e,hotel.checkin,hotel.checkout FROM [resvlog],[hotel] where    confnum=@Confnum and (resvlog.propertyid=hotel.pid or resvlog.propertyid=hotel.pid_e)
        and verifycode in(select top 1  verifycode from  jj_carduser_bookresv where cardnumber=@cardnumber  and Confnum=@Confnum)
        end
 else
    begin
        SELECT resvlog.*,hotel.phone,hotel.address1,hotel.address1_e,hotel.checkin,hotel.checkout FROM [resvlog],[hotel] where    confnum=@Confnum and (resvlog.propertyid=hotel.pid or resvlog.propertyid=hotel.pid_e)
        and guestlastname=@LastName
        end
go


create procedure dbo.FGB_JJ_ResvLog_Add @userid int,
 @usertype nvarchar(50),
 @propertyid int,
 @roomtype nvarchar(50),
 @rateclass nvarchar(50),
 @starttime datetime,
 @deptime datetime,
 @updatetime datetime,
 @nights int,
 @room int,
 @guestfirstname nvarchar(50),
 @guestlastname nvarchar(50),
 @guestemail nvarchar(50),
 @guestphone nvarchar(50),
 @guestMP nvarchar(50),
 @guestaddressline1 nvarchar(50),
 @guestaddressline2 nvarchar(50),
 @guestcity nvarchar(50),
 @guestcountry nvarchar(50),
 @gueststate nvarchar(50),
 @guestzip nvarchar(50),
 @cctype nvarchar(50),
 @ccnumber nvarchar(50),
 @ccname nvarchar(50),
 @ccexpyear nvarchar(50),
 @ccexpmonth nvarchar(50),
 @frequentguestid nvarchar(50),
 @iata nvarchar(50),
 @remarks ntext,
 @confnum nvarchar(50),
 @cxlnum nvarchar(50),
 @status nvarchar(50),
 @propertyname nvarchar(500),
 @propertyname_e nvarchar(500),
 @totalmount nvarchar(50),
 @dailyprice nvarchar(500),
 @adults int,
 @children int,
 @plandesc varchar(500),
 @roomname varchar(500),
 @roomdesc varchar(500),
 @canclerule nvarchar(500),
 @guaranteerule nvarchar(500),
 @taxrule nvarchar(500),
 @incomingcall nvarchar(50),
 @fromurl nvarchar(255),
 @deleted int,
 @SubSource nvarchar(50),
 @lastuser nvarchar(50),
 @lastusertype nvarchar(50),
 @verifycode nvarchar(50),
 @getstatus int,
 @flgorder int,
 @departure datetime,
 @payment nvarchar(50),
 @cardnumber as
nvarchar(50),
@isscore as bit,
@isspecial as bit,
@jremark as nvarchar(500),
@score as decimal(18,4),
@islock as bit,
@isexec as bit,
@freezeno as nvarchar(50),
@comment as nvarchar(500)
as
insert into
 resvlog(userid,usertype,propertyid,roomtype,rateclass,starttime,deptime,updatetime,nights,room,guestfirstname,guestlastname,guestemail,guestphone,guestMP,guestaddressline1,guestaddressline2,guestcity,guestcountry,gueststate,guestzip,cctype,ccnumber,ccname,ccexpyear,ccexpmonth,frequentguestid,iata,remarks,confnum,cxlnum,status,propertyname,propertyname_e,totalmount,dailyprice,adults,children,plandesc,roomname,roomdesc,canclerule,guaranteerule,taxRule,incomingcall,fromurl,deleted,SubSource,lastuser,lastuser
type,verifycode,getstatus,flgorder,departure,payment)
 values(@userid,@usertype,@propertyid,@roomtype,@rateclass,@starttime,@deptime,@updatetime,@nights,@room,@guestfirstname,@guestlastname,@guestemail,@guestphone,@guestMP,@guestaddressline1,@guestaddressline2,@guestcity,@guestcountry,@gueststate,@guestzip,@cctype,@ccnumber,@ccname,@ccexpyear,@ccexpmonth,@frequentguestid,@iata,@remarks,@confnum,@cxlnum,@status,@propertyname,@propertyname_e,@totalmount,@dailyprice,@adults,@children,@plandesc,@roomname,@roomdesc,@canclerule,@guaranteerule,@taxrule,@incomingcall
,@fromurl,@deleted,@SubSource,@lastuser,@lastusertype,@verifycode,@getstatus,@flgorder,@departure,@payment);
if len(@cardnumber)>0
begin
insert into  jj_carduser_bookresv
(cardnumber,verifycode,isscore,isspecial,remark,score,islock,isexec,freezeno,comment)values
(@cardnumber,@verifycode,@isscore,@isspecial,@jremark,@score,@islock,@isexec,@freezeno,@comment)
end
go


create procedure dbo.FGB_JJ_ResvLog_Mod @userid int,
 @usertype nvarchar(50),
 @propertyid int,
 @roomtype nvarchar(50),
 @rateclass nvarchar(50),
 @starttime datetime,
 @deptime datetime,
 @updatetime datetime,
 @nights int,
 @room int,
 @guestfirstname nvarchar(50),
 @guestlastname nvarchar(50),
 @guestemail nvarchar(50),
 @guestphone nvarchar(50),
 @guestMP nvarchar(50),
 @guestaddressline1 nvarchar(50),
 @guestaddressline2 nvarchar(50),
 @guestcity nvarchar(50),
 @guestcountry nvarchar(50),
 @gueststate nvarchar(50),
 @guestzip nvarchar(50),
 @cctype nvarchar(50),
 @ccnumber nvarchar(50),
 @ccname nvarchar(50),
 @ccexpyear nvarchar(50),
 @ccexpmonth nvarchar(50),
 @frequentguestid nvarchar(50),
 @iata nvarchar(50),
 @remarks ntext,
 @confnum nvarchar(50),
 @cxlnum nvarchar(50),
 @status nvarchar(50),
 @propertyname nvarchar(500),
 @propertyname_e nvarchar(500),
 @totalmount nvarchar(50),
 @dailyprice varchar(2000),
 @adults int,
 @children int,
 @plandesc varchar(500),
 @roomname varchar(500),
 @roomdesc varchar(500),
 @canclerule nvarchar(500),
 @guaranteerule nvarchar(500),
 @taxrule nvarchar(500),
 @incomingcall nvarchar(50),
 @fromurl nvarchar(255),
 @deleted int,
 @SubSource nvarchar(50),
 @lastuser nvarchar(50),
 @lastusertype nvarchar(50),
 @verifycode nvarchar(50) as
update resvlog set 
 userid=@userid,usertype=@usertype,propertyid=@propertyid,roomtype=@roomtype,rateclass=@rateclass,starttime=@starttime,deptime=@deptime,updatetime=@updatetime,nights=@nights,room=@room,guestfirstname=@guestfirstname,guestlastname=@guestlastname,guestemail=@guestemail,guestphone=@guestphone,guestMP=@guestMP,guestaddressline1=@guestaddressline1,guestaddressline2=@guestaddressline2,guestcity=@guestcity,guestcountry=@guestcountry,gueststate=@gueststate,guestzip=@guestzip,cctype=@cctype,ccnumber=@ccnumber,ccnam
e=@ccname,ccexpyear=@ccexpyear,ccexpmonth=@ccexpmonth,frequentguestid=@frequentguestid,iata=@iata,remarks=@remarks,confnum=@confnum,cxlnum=@cxlnum,status=@status,propertyname=@propertyname,propertyname_e=@propertyname_e,totalmount=@totalmount,dailyprice=@dailyprice,adults=@adults,children=@children,plandesc=@plandesc,roomname=@roomname,roomdesc=@roomdesc,canclerule=@canclerule,guaranteerule=@guaranteerule,taxRule=@taxrule,incomingcall=@incomingcall,fromurl=@fromurl,deleted=@deleted,SubSource=@SubSource,las
tuser=@lastuser,lastusertype=@lastusertype,verifycode=@verifycode where propertyid=@propertyid and verifycode=@verifycode
go


create procedure dbo.FGB_JJ_ResvLog_Sel @verifycode nvarchar(50) as
select a.*,b.comment from ( select * from  resvlog where verifycode=@verifycode) a left join jj_carduser_bookresv b on a.verifycode=b.verifycode and   a.verifycode=@verifycode
go


create procedure dbo.FGB_JJ_SelectTAX (
 	@Property_id int
 	) as
select * from H_tax where property_id=@Property_id
go


create procedure dbo.FGB_JJ_selectHotel (
 	@Hotel_ID int
 	) as
select * from hotel where Hotel_ID=@Hotel_ID
go


create procedure dbo.FGB_hweb_user_Insert_Web @gid as
int ,@username as varchar(50),@email as varchar(200),@mobnumb  as varchar(20),@pwd as varchar(50),@usercheckcode as varchar(50),@ademail as bit,@admobile as bit
as 
begin
        begin Transaction 
                declare @uid as int;
                insert into  hweb_user(gid,usrpassword,usremail,usrmobile,usercheckcode,ademail,admobile,Checkcodedate)values(@gid,@pwd,@email,@mobnumb,@usercheckcode,@ademail,@admobile,getdate());
                select @uid=SCOPE_IDENTITY()
               
                if @username!=''
                begin
                   insert into hweb_user_username(gid,uid,username)values(@gid,@uid,@username);
                end
                if @email!=''
                begin
                   insert into hweb_user_email(gid,uid,email)values(@gid,@uid,@email);
                end
                if @mobnumb!=''
                begin
                    insert into hweb_user_mobile(gid,uid,mobnumb)values(@gid,@uid,@mobnumb);
                end        
        if @@error=0
        commit Transaction
        else
        rollback Transaction
end
go


create procedure dbo.FGB_hweb_user_IsExist @gid as
int ,@value as varchar(50),@type as varchar(20)
as
begin
        if @Type='username'
        begin
          select count(*) from hweb_user_username where gid=@gid and username=@value;
        end
        if @Type='email'
        begin
          select count(*) from hweb_user_email where gid=@gid and email=@value;
        end
        if @Type='mobile'
        begin
          select count(*) from hweb_user_mobile where gid=@gid and mobnumb=@value;
        end
        if @Type='cardnumber'
        begin
          select count(*) from hweb_user_cardnumber where gid=@gid and cardnumber=@value;
        end
end
go


create procedure dbo.FITEN_GetPage @sql as
nvarchar(4000),@key as nvarchar(100),@field as nvarchar(100),@pagesize as int,@PageIndex as int,@sort as bit
as 


if @sort=1
	begin
	if @key=@field
		begin
		set @sql='select * from ( select '+@sql+')a where '+@key+' in (select '+@key+' from (select top  '+str(@pagesize*@PageIndex)+@sql+'  order by '+@key+' desc)a)and '+@key+' not in (select '+@key+' from (select top '+str(@pagesize*@PageIndex-@pagesize)+'  '+@sql+' order by '+@key+' desc)a) order by '+@field+' desc'
		end
	else 
	        begin
		set @sql='select * from ( select '+@sql+')a where '+@key+' in (select '+@key+' from (select top  '+str(@pagesize*@PageIndex)+@sql+'  order by '+@field+' desc)a)and '+@key+' not in (select '+@key+' from (select top '+str(@pagesize*@PageIndex-@pagesize)+' '+@sql+' order by '+@field+' desc)a) order by '+@field+' desc'
		end
	end
else	
	begin
	if @key=@field
                begin
                 set @sql='select * from ( select '+@sql+')a where '+@key+' in (select '+@key+' from (select top  '+str(@pagesize*@PageIndex)+@sql+'  order by  '+@key+' asc)a)and '+@key+' not in (select '+@key+' from (select top '+str(@pagesize*@PageIndex-@pagesize)+'  '+@sql+' order by  '+@key+' asc)a) order by '+@field+' asc'
                end
		
	else
	        begin
		set @sql='select * from ( select '+@sql+')a where '+@key+' in (select '+@key+' from (select top  '+str(@pagesize*@PageIndex)+@sql+'  order by '+@field+' asc)a)and '+@key+' not in (select '+@key+' from (select top '+str(@pagesize*@PageIndex-@pagesize)+'  '+@sql+' order by '+@field+' asc)a) order by '+@field+' asc'
	        end
        end
exec( @sql)
go


create procedure dbo.FITJSon_GetResvAll_byName @Confnum nvarchar(50),@LastName as
nvarchar(50)
as
declare @verifycode as nvarchar(50);
declare @MyConfnum nvarchar(50)
    
    set @Confnum=replace(@Confnum,'''','''''') 
    set @Confnum=replace(@Confnum,'--','') 
    set @Confnum=replace(@Confnum,';','')
    set @LastName=replace(@LastName,'''','''''') 
    set @LastName=replace(@LastName,'--','') 
    set @LastName=replace(@LastName,';','')
set @MyConfnum =@Confnum
SELECT @verifycode=verifycode FROM [resvlog] where  guestlastname=@LastName and confnum=@MyConfnum;
SELECT 
a.[id], 
a.[userid],
 a.[usertype],
 a.[propertyid],
 a.[roomtype],
 a.[rateclass], 
dbo.FIT_ChangeDate(a.[starttime],'cn') as starttime, 
dbo.FIT_ChangeDate(a.[deptime],'cn') as deptime, 
a.[departure], 
a.[nights], 
a.[room], 
a.[guestfirstname], 
a.[guestlastname],
 a.[guestemail], 
a.[guestphone],
 a.[guestMP], 
a.[guestaddressline1],
 a.[guestaddressline2], 
a.[guestcity], 
a.[guestcountry],
 a.[gueststate], 
a.[guestzip], 
a.[remarks], 
a.[confnum],
 a.[cxlnum], 
a.[status], 
a.[propertyname],
 a.[propertyname_e], 
a.[totalmount],
 a.[dailyprice], 
a.[adults], 
a.[children],
 a.[plandesc], 
a.[roomname],
 a.[roomdesc], 
a.[canclerule], 
a.[guaranteerule],
 a.[taxRule],
a.[deleted],
a.[getstatus], 
a.[totalrevenue],
 a.[verifycode], 
 a.[payment], 
a.[outconfnum], 
b.title,
b.title_e,
b.address1,
b.address1_e,
b.phone,
dbo.FIT_ChangeTime(b.checkin) as checkin,
dbo.FIT_ChangeTime(b.checkout) as checkout,
dbo.GetCCCardNames(b.fop,'1') as fop,
c.payman,
case when (a.ccname='-' and a.ccnumber='-' and   a.ccexpyear='00' and   a.ccexpmonth='00') then
 ''
else 'You have now guaranteed your booking with credit card.' end  as ccemail_en,
case when (a.ccname='-' and a.ccnumber='-' and   a.ccexpyear='00' and   a.ccexpmonth='00') then
 ''
else '您已使用信用卡确认您的订单。' end  as ccemail_cn,
dbo.GetCCCardName(cctype) as cctypename,
dbo.ECCCnumber(ccnumber) as enccnumber
 FROM 
[resvlog] as a 
left join pay c
on a.confnum=c.confnum
inner join [hotel] as b 
on (a.propertyid=b.pid or a.propertyid=b.pid_e) and  a.verifycode=@verifycode
go


create procedure dbo.FITJson_MailGetResvAll_GUID @verifycode nvarchar(50) as
declare @MyConfnum nvarchar(50)
    
    set @verifycode=replace(@verifycode,'''','''''') 
    set @verifycode=replace(@verifycode,'--','') 
    set @verifycode=replace(@verifycode,';','') 
SELECT 
a.[id], 
a.[userid],
 a.[usertype],
 a.[propertyid],
 a.[roomtype],
 a.[rateclass], 
dbo.FIT_ChangeDate(a.[starttime],'cn') as starttime, 
dbo.FIT_ChangeDate(a.[deptime],'cn') as deptime, 
a.[departure], 
a.[nights], 
a.[room], 
a.[guestfirstname], 
a.[guestlastname],
 a.[guestemail], 
a.[guestphone],
 a.[guestMP], 
a.[guestaddressline1],
 a.[guestaddressline2], 
a.[guestcity], 
a.[guestcountry],
 a.[gueststate], 
a.[guestzip], 
a.[cctype], 
a.[ccnumber], 
a.[ccname], 
a.[ccexpyear], 
a.[ccexpmonth], 
a.[frequentguestid], 
a.[iata], 
a.[remarks], 
a.[confnum],
 a.[cxlnum], 
a.[status], 
a.[propertyname],
 a.[propertyname_e], 
a.[totalmount],
 a.[dailyprice], 
a.[adults], 
a.[children],
 a.[plandesc], 
a.[roomname],
 a.[roomdesc], 
a.[canclerule], 
a.[guaranteerule],
 a.[taxRule],
 a.[incomingcall], 
a.[fromurl], 
a.[deleted],
dbo.FIT_ChangeDate(a.[updatetime],'cn') as updatetime,
 a.[ccupdatetime], 
a.[SubSource], 
a.[lastuser], 
a.[lastusertype], 
a.[getstatus], 
a.[totalrevenue],
 a.[verifycode], 
a.[flgorder],
 a.[pmsno], 
a.[roomno], 
a.[deplistno],
 a.[payment], 
a.[outconfnum], 
a.[starture],
 a.[conftime], 
a.[fit_userid],
a.[channel],
b.title,
b.title_e,
b.address1,
b.address1_e,
b.phone,
dbo.FIT_ChangeTime(b.checkin) as checkin,
dbo.FIT_ChangeTime(b.checkout) as checkout,
dbo.GetCCCardNames(b.fop,'1') as fop,
c.payman,
case when (a.ccname='-' and a.ccnumber='-' and   a.ccexpyear='00' and   a.ccexpmonth='00') then
 ''
else 'You have now guaranteed your booking with credit card.' end  as ccemail_en,
case when (a.ccname='-' and a.ccnumber='-' and   a.ccexpyear='00' and   a.ccexpmonth='00') then
 ''
else '您已使用信用卡确认您的订单。' end  as ccemail_cn,
dbo.GetCCCardName(cctype) as cctypename,
dbo.ECCCnumber(ccnumber) as enccnumber
 FROM 
[resvlog] as a 
left join pay c
on a.confnum=c.confnum
inner join [hotel] as b 
on (a.propertyid=b.pid or a.propertyid=b.pid_e) and  a.verifycode=@verifycode
go


create procedure dbo.FIT_BookingRecord @userid as
int ,@fit_userid as nvarchar(500),@pagesize as int,@PageIndex as int
as 
declare @SQL as varchar(8000);
set @SQL='';
select a.[id],a.fit_userid,Convert(varchar(10),a.updatetime,120) as updatetime,isnull(a.propertyname,'') as propertyname, Convert(varchar(10),a.starttime,120) as starttime,
Convert(varchar(10),a.deptime,120) as deptime,a.room,a.totalmount,(case a.getstatus when 0 then '新单' when 1 then '已处理' when 4 then '取消' when 5 then '应到未到' when 7  then '入住' else '离店'  end) as getstatus,a.confnum,b.stars,b.diamond,isnull(c.[Name],'') as ClassName into #tempsort from 
resvlog as a 
left join hotel as b
on a.propertyid=b.pid
left join H_city as c
on b.Cityid=c.cityid
where a.userid=@userid and a.fit_userid=@fit_userid and (a.getstatus='0' or a.getstatus='4' or a.getstatus='5' or a.getstatus='7' or a.getstatus='8') and a.confnum!=''  order by getstatus asc,updatetime asc
select @@rowcount;
set @sql=@sql+'select * from #tempsort where [id] in (select [id] from (select top  '+str(@pagesize*@PageIndex)+' [id] from #tempsort   order by updatetime asc)a)and [id] not in (select [id] from (select top '+str(@pagesize*@PageIndex-@pagesize)+' [id] from #tempsort  order by updatetime asc)a) order by updatetime asc;'
set @sql=@sql+'drop table #tempsort';
exec( @sql);
go


create function dbo.FIT_ChangeDate (@date as datetime,@Lan as varchar(10))
returns nvarchar(20) 
as 
begin
declare @temp as varchar(20);
declare @mname as varchar(200);
declare @m as int;
set @m=month(@date)
set @mname='Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec';
if @Lan='cn'
  set @temp=Convert(varchar(10),@date,120);
else 
begin
set @temp=substring(@mname,(@m-1)*4+1,3)+'-'+ right('0'+Convert(varchar,day(@date)),2)
	+'-'+right('0'+Convert(varchar,year(@date)),4)
end
return @temp;

end
go


create function dbo.FIT_ChangeTime (@time as varchar(50))
returns nvarchar(50) 
as 
begin
set @time='1200'
if len(@time)=1
   set @time='0'+@time+'00';
else if len(@time)=2
    set @time=@time+'00';
else if len(@time)=3
 set @time='0'+@time;
set @time=left(@time,2)+':'+right(@time,2)
return @time;

end
go


create procedure dbo.FIT_GetResvAll @Confnum nvarchar(50),@guestMp as
nvarchar(12),@fit_userid as uniqueidentifier
as
declare @MyConfnum nvarchar(50)
    
    set @Confnum=replace(@Confnum,'''','''''') 
    set @Confnum=replace(@Confnum,'--','') 
    set @Confnum=replace(@Confnum,';','')
    set @guestMp=replace(@guestMp,'''','''''') 
    set @guestMp=replace(@guestMp,'--','') 
    set @guestMp=replace(@guestMp,';','')
set @MyConfnum =@Confnum
if @guestMP=''
begin
SELECT resvlog.*,hotel.phone,hotel.address1,hotel.address1_e,hotel.checkin,hotel.checkout FROM [resvlog],[hotel] where  fit_userid=@fit_userid and confnum=@MyConfnum and (resvlog.propertyid=hotel.pid or resvlog.propertyid=hotel.pid_e)  
end
else
 begin
SELECT resvlog.*,hotel.phone,hotel.address1,hotel.address1_e,hotel.checkin,hotel.checkout FROM [resvlog],[hotel] where  guestMp=@guestMp and confnum=@MyConfnum   and(resvlog.propertyid=hotel.pid or resvlog.propertyid=hotel.pid_e)

end
go


create procedure dbo.FIT_GetResvAll_byName @Confnum nvarchar(50),@LastName as
nvarchar(50),@fit_userid as uniqueidentifier
as
declare @MyConfnum nvarchar(50)
    
    set @Confnum=replace(@Confnum,'''','''''') 
    set @Confnum=replace(@Confnum,'--','') 
    set @Confnum=replace(@Confnum,';','')
    set @LastName=replace(@LastName,'''','''''') 
    set @LastName=replace(@LastName,'--','') 
    set @LastName=replace(@LastName,';','')
set @MyConfnum =@Confnum
if @LastName=''
begin
SELECT resvlog.*,hotel.phone,hotel.address1,hotel.address1_e,hotel.checkin,hotel.checkout FROM [resvlog],[hotel] where  fit_userid=@fit_userid and confnum=@MyConfnum and (resvlog.propertyid=hotel.pid or resvlog.propertyid=hotel.pid_e)  
end
else
 begin
SELECT resvlog.*,hotel.phone,hotel.address1,hotel.address1_e,hotel.checkin,hotel.checkout FROM [resvlog],[hotel] where  guestlastname=@LastName and confnum=@MyConfnum   and(resvlog.propertyid=hotel.pid or resvlog.propertyid=hotel.pid_e)

end
go


create procedure dbo.FIT_GetUserInfoPage @UserID as
int,@date1 as varchar(10),@date2 as varchar(10),@pagesize as int,@PageIndex as int
as 
declare @SQL as varchar(8000);
declare @d1 as datetime,@d2 as datetime;
if(len(@date1)=0 and  len(@date2)=0)
begin
set @d1='1900-01-01';
set @d2=getdate();
end
else if(@date1='' and @date2!='')
begin
 set @d1=@date2;
 set @d2=@date2;
end
else if(@date1!='' and @date2='')
begin
 set @d1=@date1;
 set @d2=@date1;
end
else 
begin
   set @d1=@date1;
 set @d2=@date2;
  if(@d1>@d2)
   begin
    set @d1=@date2;
    set @d2=@date1;
   end   
end
  set @d2=dateadd(d,1,@d2)
set @SQL='';
select a.UserID as fit_userid,a.TAUserID,g.IATA,isnull(h.UserName,'') as UserName, isnull(a.UName,'') as UName,b.Email, (case when a.MobilePhone is null then '-' else a.MobilePhone end) as MobilePhone, (case when a.Phone is null then '-' else a.Phone end) as Phone,
(case when a.LogTimes is null then 0 else a.LogTimes end) as LogTimes, isnull(c.orderNum,0) as orderNum,(case when d.checkin is null then 0 else d.checkin end) as checkin, (case when e.cancel is null then 0 else e.cancel end) as cancel, isnull(f.noshow,0) as noshow,convert(varchar(10),b.createdate,120) as createdate  into #tempsort from 
(select TAUserID,UserID,LastName+' '+FirstName as UName,MobilePhone,Phone,LogTimes from FIT_Profile where TAuserID=@userid) a
inner join 
(select UserID,Email,dateadd(hh,8,createdate)as createdate from aspnet_Membership where @d1<=dateadd(hh,8,createdate) and dateadd(hh,8,createdate)<@d2 )b on a.UserID=b.UserID
left join 
(select fit_userid, count(*) as ordernum from resvlog where userid=@userid  group by fit_userid)c on a.UserID=c.fit_userid
left join 
(select fit_userid, count(*) as checkin from resvlog where userid=@userid and (getstatus=7 or  getstatus=8)  group by fit_userid)d on a.UserID=d.fit_userid
left join
(select fit_userid, count(*) as cancel from resvlog where userid=@userid and  status like 'cxl'  group by fit_userid)e on a.UserID=e.fit_userid
left join 
(select fit_userid, count(*) as noshow from resvlog where userid=@userid and getstatus=5  group by fit_userid)f on a.UserID=f.fit_userid
left join
(select a.IATA,b.UserID from Corp a inner join  [user] b on a.corp_id=b.parentid and userid=@userid)g on a.TAUserID=g.userid
inner join 
(select UserID,UserName from aspnet_Users)h on a.UserID=h.UserID

select @@rowcount;
set @sql=@sql+'select * from #tempsort where fit_userid in (select fit_userid from (select top  '+str(@pagesize*@PageIndex)+' fit_userid from #tempsort   order by createdate desc)a)and fit_userid not in (select fit_userid from (select top '+str(@pagesize*@PageIndex-@pagesize)+' fit_userid from #tempsort  order by createdate desc)a) order by createdate desc;'
set @sql=@sql+'drop table #tempsort';
print(@sql)
exec( @sql);
go


create procedure dbo.FIT_GetUserInfoPage2 @UserID as
int,@date1 as varchar(10),@date2 as varchar(10),@pagesize as int,@PageIndex as int
as 
declare @SQL as varchar(8000);
declare @d1 as datetime,@d2 as datetime;
if(len(@date1)=0 and  len(@date2)=0)
begin
set @d1='1900-01-01';
set @d2=getdate();
end
else if(@date1='' and @date2!='')
begin
 set @d1=@date2;
 set @d2=@date2;
end
else if(@date1!='' and @date2='')
begin
 set @d1=@date1;
 set @d2=@date1;
end
else 
begin
   set @d1=@date1;
 set @d2=@date2;
  if(@d1>@d2)
   begin
    set @d1=@date2;
    set @d2=@date1;
   end   
end
  set @d2=dateadd(d,1,@d2)
set @SQL='';
select a.UserID as fit_userid,a.TAUserID,g.IATA,isnull(h.UserName,'') as UserName, isnull(a.UName,'') as UName,b.Email, (case when a.MobilePhone is null then '-' else a.MobilePhone end) as MobilePhone, (case when a.Phone is null then '-' else a.Phone end) as Phone,
(case when a.LogTimes is null then 0 else a.LogTimes end) as LogTimes, isnull(c.orderNum,0) as orderNum,(case when d.checkin is null then 0 else d.checkin end) as checkin, (case when e.cancel is null then 0 else e.cancel end) as cancel, isnull(f.noshow,0) as noshow,convert(varchar(10),b.createdate,120) as createdate  into #tempsort from 
(select TAUserID,UserID,LastName+' '+FirstName as UName,MobilePhone,Phone,LogTimes from FIT_Profile where TAuserID=@userid) a
inner join 
(select UserID,Email,dateadd(hh,8,createdate)as createdate from aspnet_Membership where @d1<=dateadd(hh,8,createdate) and dateadd(hh,8,createdate)<@d2 )b on a.UserID=b.UserID
left join 
(select fit_userid, count(*) as ordernum from resvlog where userid=@userid  group by fit_userid)c on a.UserID=c.fit_userid
left join 
(select fit_userid, count(*) as checkin from resvlog where userid=@userid and (getstatus=7 or  getstatus=8)  group by fit_userid)d on a.UserID=d.fit_userid
left join
(select fit_userid, count(*) as cancel from resvlog where userid=@userid and  status like 'cxl'  group by fit_userid)e on a.UserID=e.fit_userid
left join 
(select fit_userid, count(*) as noshow from resvlog where userid=@userid and getstatus=5  group by fit_userid)f on a.UserID=f.fit_userid
left join
(select a.IATA,b.UserID from Corp a inner join  [user] b on a.corp_id=b.parentid and userid=@userid)g on a.TAUserID=g.userid
inner join 
(select UserID,UserName from aspnet_Users)h on a.UserID=h.UserID

select @@rowcount;
set @sql=@sql+'select * from #tempsort where fit_userid in (select fit_userid from (select top  '+str(@pagesize*@PageIndex)+' fit_userid from #tempsort   order by createdate desc)a)and fit_userid not in (select fit_userid from (select top '+str(@pagesize*@PageIndex-@pagesize)+' fit_userid from #tempsort  order by createdate desc)a) order by createdate desc;'
set @sql=@sql+'drop table #tempsort';
exec( @sql);
go


create procedure dbo.FIT_GetUserInfoPage_1 @UserID as
int,@date1 as varchar(10),@date2 as varchar(10),@pagesize as int,@PageIndex as int
as 
declare @SQL as varchar(8000);
declare @d1 as datetime,@d2 as datetime;
if(len(@date1)=0 and  len(@date2)=0)
begin
set @d1='1900-01-01';
set @d2=getdate();
end
else if(@date1='' and @date2!='')
begin
 set @d1=@date2;
 set @d2=@date2;
end
else if(@date1!='' and @date2='')
begin
 set @d1=@date1;
 set @d2=@date1;
end
else 
begin
   set @d1=@date1;
 set @d2=@date2;
  if(@d1>@d2)
   begin
    set @d1=@date2;
    set @d2=@date1;
   end   
end
  set @d2=dateadd(d,1,@d2)
set @SQL='';
select a.UserID as fit_userid,a.TAUserID,g.IATA,h.UserName as 用户名,a.UName as 姓名 ,b.Email as 电子邮箱,a.MobilePhone as 手机,a.Phone as 电话,
a.LogTimes as 登录次数,c.orderNum as 预订,d.checkin as 入住,e.cancel as 取消,f.noshow as NOSHOW,b.createdate  into #tempsort from 
(select TAUserID,UserID,LastName+' '+FirstName as UName,MobilePhone,Phone,LogTimes from FIT_Profile where TAuserID=@userid) a
inner join 
(select UserID,Email,dateadd(hh,8,createdate)as createdate from aspnet_Membership where @d1<=dateadd(hh,8,createdate) and dateadd(hh,8,createdate)<@d2 )b on a.UserID=b.UserID
left join 
(select fit_userid, count(*) as ordernum from resvlog where userid=@userid  group by fit_userid)c on a.UserID=c.fit_userid
left join 
(select fit_userid, count(*) as checkin from resvlog where userid=@userid and (getstatus=7 or  getstatus=8)  group by fit_userid)d on a.UserID=d.fit_userid
left join
(select fit_userid, count(*) as cancel from resvlog where userid=@userid and  status like 'cxl'  group by fit_userid)e on a.UserID=e.fit_userid
left join 
(select fit_userid, count(*) as noshow from resvlog where userid=@userid and getstatus=5  group by fit_userid)f on a.UserID=f.fit_userid
left join
(select a.IATA,b.UserID from Corp a inner join  [user] b on a.corp_id=b.parentid and userid=@userid)g on a.TAUserID=g.userid
inner join 
(select UserID,UserName from aspnet_Users)h on a.UserID=h.UserID

select @@rowcount;
set @sql=@sql+'select * from #tempsort where fit_userid in (select fit_userid from (select top  '+str(@pagesize*@PageIndex)+' fit_userid from #tempsort   order by createdate desc)a)and fit_userid not in (select fit_userid from (select top '+str(@pagesize*@PageIndex-@pagesize)+' fit_userid from #tempsort  order by createdate desc)a) order by createdate desc;'
set @sql=@sql+'drop table #tempsort';
exec( @sql);












go


create procedure dbo.FIT_MailGetResvAll @Confnum nvarchar(50) as
declare @MyConfnum nvarchar(50)
    
    set @Confnum=replace(@Confnum,'''','''''') 
    set @Confnum=replace(@Confnum,'--','') 
    set @Confnum=replace(@Confnum,';','') 
set @MyConfnum =@Confnum
SELECT 
a.[id], 
a.[userid],
 a.[usertype],
 a.[propertyid],
 a.[roomtype],
 a.[rateclass], 
dbo.FIT_ChangeDate(a.[starttime],'cn') as starttime, 
dbo.FIT_ChangeDate(a.[deptime],'cn') as deptime, 
a.[departure], 
a.[nights], 
a.[room], 
a.[guestfirstname], 
a.[guestlastname],
 a.[guestemail], 
a.[guestphone],
 a.[guestMP], 
a.[guestaddressline1],
 a.[guestaddressline2], 
a.[guestcity], 
a.[guestcountry],
 a.[gueststate], 
a.[guestzip], 
a.[cctype], 
a.[ccnumber], 
a.[ccname], 
a.[ccexpyear], 
a.[ccexpmonth], 
a.[frequentguestid], 
a.[iata], 
a.[remarks], 
a.[confnum],
 a.[cxlnum], 
a.[status], 
a.[propertyname],
 a.[propertyname_e], 
a.[totalmount],
 a.[dailyprice], 
a.[adults], 
a.[children],
 a.[plandesc], 
a.[roomname],
 a.[roomdesc], 
a.[canclerule], 
a.[guaranteerule],
 a.[taxRule],
 a.[incomingcall], 
a.[fromurl], 
a.[deleted],
dbo.FIT_ChangeDate(a.[updatetime],'cn') as updatetime,
 a.[ccupdatetime], 
a.[SubSource], 
a.[lastuser], 
a.[lastusertype], 
a.[getstatus], 
a.[totalrevenue],
 a.[verifycode], 
a.[flgorder],
 a.[pmsno], 
a.[roomno], 
a.[deplistno],
 a.[cclog], 
a.[ccdanbao],
 a.[payment], 
a.[confnumType], 
a.[outconfnum], 
a.[starture],
 a.[conftime], 
a.[fit_userid],
a.[channel],
b.title,
b.title_e,
b.address1,
b.address1_e,
b.phone,
dbo.FIT_ChangeTime(b.checkin) as checkin,
dbo.FIT_ChangeTime(b.checkout) as checkout,
b.fop,
c.payman,
Convert(decimal(18,2),a.totalmount/e.rate) as USD
 FROM 
[resvlog] as a 
left join pay c
on a.confnum=c.confnum
left join ExchangeRate e
on e.currency like 'USD'
inner join [hotel] as b 
on (a.propertyid=b.pid or a.propertyid=b.pid_e) and  a.confnum=@MyConfnum
go


create procedure dbo.FIT_MailGetResvAll_GUID @verifycode nvarchar(50) as
declare @MyConfnum nvarchar(50)
    
    set @verifycode=replace(@verifycode,'''','''''') 
    set @verifycode=replace(@verifycode,'--','') 
    set @verifycode=replace(@verifycode,';','') 
SELECT 
a.[id], 
a.[userid],
 a.[usertype],
 a.[propertyid],
 a.[roomtype],
 a.[rateclass], 
dbo.FIT_ChangeDate(a.[starttime],'cn') as starttime, 
dbo.FIT_ChangeDate(a.[deptime],'cn') as deptime, 
a.[departure], 
a.[nights], 
a.[room], 
a.[guestfirstname], 
a.[guestlastname],
 a.[guestemail], 
a.[guestphone],
 a.[guestMP], 
a.[guestaddressline1],
 a.[guestaddressline2], 
a.[guestcity], 
a.[guestcountry],
 a.[gueststate], 
a.[guestzip], 
a.[cctype], 
a.[ccnumber], 
a.[ccname], 
a.[ccexpyear], 
a.[ccexpmonth], 
a.[frequentguestid], 
a.[iata], 
a.[remarks], 
a.[confnum],
 a.[cxlnum], 
a.[status], 
a.[propertyname],
 a.[propertyname_e], 
a.[totalmount],
 a.[dailyprice], 
a.[adults], 
a.[children],
 a.[plandesc], 
a.[roomname],
 a.[roomdesc], 
a.[canclerule], 
a.[guaranteerule],
 a.[taxRule],
 a.[incomingcall], 
a.[fromurl], 
a.[deleted],
dbo.FIT_ChangeDate(a.[updatetime],'cn') as updatetime,
 a.[ccupdatetime], 
a.[SubSource], 
a.[lastuser], 
a.[lastusertype], 
a.[getstatus], 
a.[totalrevenue],
 a.[verifycode], 
a.[flgorder],
 a.[pmsno], 
a.[roomno], 
a.[deplistno],
 a.[cclog], 
a.[ccdanbao],
 a.[payment], 

a.[outconfnum], 
a.[starture],
 a.[conftime], 
a.[fit_userid],
a.[channel],
b.title,
b.title_e,
b.address1,
b.address1_e,
b.phone,
dbo.FIT_ChangeTime(b.checkin) as checkin,
dbo.FIT_ChangeTime(b.checkout) as checkout,
b.fop,
c.payman,
case when (a.ccname='-' and a.ccnumber='-' and   a.ccexpyear='00' and   a.ccexpmonth='00') then
 ''
else 'You have now confirmed your booking by credit card.' end  as ccemail_en,
case when (a.ccname='-' and a.ccnumber='-' and   a.ccexpyear='00' and   a.ccexpmonth='00') then
 ''
else '您已使用信用卡确认您的订单。' end  as ccemail_cn
 FROM 
[resvlog] as a 
left join pay c
on a.confnum=c.confnum
inner join [hotel] as b 
on (a.propertyid=b.pid or a.propertyid=b.pid_e) and  a.verifycode=@verifycode
go


create procedure dbo.FIT_MailGetResvAll_googleorderno @billno nvarchar(50) as
declare @MyConfnum nvarchar(50)
    
    set @billno=replace(@billno,'''','''''') 
    set @billno=replace(@billno,'--','') 
    set @billno=replace(@billno,';','') 
SELECT 
a.[id], 
a.[userid],
 a.[usertype],
 a.[propertyid],
 a.[roomtype],
 a.[rateclass], 
dbo.FIT_ChangeDate(a.[starttime],'cn') as starttime, 
dbo.FIT_ChangeDate(a.[deptime],'cn') as deptime, 
a.[departure], 
a.[nights], 
a.[room], 
a.[guestfirstname], 
a.[guestlastname],
 a.[guestemail], 
a.[guestphone],
 a.[guestMP], 
a.[guestaddressline1],
 a.[guestaddressline2], 
a.[guestcity], 
a.[guestcountry],
 a.[gueststate], 
a.[guestzip], 
a.[cctype], 
a.[ccnumber], 
a.[ccname], 
a.[ccexpyear], 
a.[ccexpmonth], 
a.[frequentguestid], 
a.[iata], 
a.[remarks], 
a.[confnum],
 a.[cxlnum], 
a.[status], 
a.[propertyname],
 a.[propertyname_e], 
a.[totalmount],
 a.[dailyprice], 
a.[adults], 
a.[children],
 a.[plandesc], 
a.[roomname],
 a.[roomdesc], 
a.[canclerule], 
a.[guaranteerule],
 a.[taxRule],
 a.[incomingcall], 
a.[fromurl], 
a.[deleted],
dbo.FIT_ChangeDate(a.[updatetime],'cn') as updatetime,
 a.[ccupdatetime], 
a.[SubSource], 
a.[lastuser], 
a.[lastusertype], 
a.[getstatus], 
a.[totalrevenue],
 a.[verifycode], 
a.[flgorder],
 a.[pmsno], 
a.[roomno], 
a.[deplistno],
 a.[cclog], 
a.[ccdanbao],
 a.[payment], 
a.[confnumType], 
a.[outconfnum], 
a.[starture],
 a.[conftime], 
a.[fit_userid],
a.[channel],
b.title,
b.title_e,
b.address1,
b.address1_e,
b.phone,
dbo.FIT_ChangeTime(b.checkin) as checkin,
dbo.FIT_ChangeTime(b.checkout) as checkout,
b.fop,
c.payman,
Convert(decimal(18,2),a.totalmount/e.rate) as USD
 FROM 
[resvlog] as a 
left join pay c
on c.confnum = a.verifycode 
left join ExchangeRate e
on e.currency like 'USD'
inner join [hotel] as b 
on (a.propertyid=b.pid or a.propertyid=b.pid_e)
where c.billno = @billno
go


create procedure dbo.FIT_MemberOrdersList @fit_userid as
varchar(40),@Lan as varchar(10),@url as varchar(200)
as 




if @lan='cn'
begin
select Propertyname as 酒店名称,
'<a href="'+@url+'?id='+convert(varchar,id)+'" target="_blank">'+confnum+'</a>' as 预订确认号,
dbo.FIT_ChangeDate(starttime,@Lan)+'/'+dbo.FIT_ChangeDate(deptime,@Lan) as [入住/离店日期]
 from resvlog where fit_userid=@fit_userid
end 
else
begin
select Propertyname as [Hotel Name],
'<a href="'+@url+'?id='+convert(varchar,id)+'" target="_blank">'+confnum+'</a>' as [Confirmation #],
dbo.FIT_ChangeDate(starttime,@Lan)+'/'+dbo.FIT_ChangeDate(deptime,@Lan) as [Check-In/Out Date]
 from resvlog where fit_userid=@fit_userid
end
go


create procedure dbo.FIT_OVS_GetPage @sql as
nvarchar(4000),@key as nvarchar(100),@field as nvarchar(100),@pagesize as int,@PageIndex as int,@sort as bit
as 


if @sort=1
	begin
	if @key=@field
		begin
		set @sql='select * from ( select '+@sql+')a where '+@key+' in (select '+@key+' from (select top  '+str(@pagesize*@PageIndex)+@sql+'  order by '+@key+' desc)a)and '+@key+' not in (select '+@key+' from (select top '+str(@pagesize*@PageIndex-@pagesize)+'  '+@sql+' order by '+@key+' desc)a) order by '+@field+' desc'
		end
	else 
	        begin
		set @sql='select * from ( select '+@sql+')a where '+@key+' in (select '+@key+' from (select top  '+str(@pagesize*@PageIndex)+@sql+'  order by '+@field+' desc)a)and '+@key+' not in (select '+@key+' from (select top '+str(@pagesize*@PageIndex-@pagesize)+' '+@sql+' order by '+@field+' desc)a) order by '+@field+' desc'
		end
	end
else	
	begin
	if @key=@field
                begin
                 set @sql='select * from ( select '+@sql+')a where '+@key+' in (select '+@key+' from (select top  '+str(@pagesize*@PageIndex)+@sql+'  order by  '+@key+' asc)a)and '+@key+' not in (select '+@key+' from (select top '+str(@pagesize*@PageIndex-@pagesize)+'  '+@sql+' order by  '+@key+' asc)a) order by '+@field+' asc'
                end
		
	else
	        begin
		set @sql='select * from ( select '+@sql+')a where '+@key+' in (select '+@key+' from (select top  '+str(@pagesize*@PageIndex)+@sql+'  order by '+@field+' asc)a)and '+@key+' not in (select '+@key+' from (select top '+str(@pagesize*@PageIndex-@pagesize)+'  '+@sql+' order by '+@field+' asc)a) order by '+@field+' asc'
	        end
        end
exec( @sql)
go


create procedure dbo.FIT_OverSeas_ResvLog_Add_Payment @userid int,
 @usertype nvarchar(50),
 @propertyid int,
 @roomtype nvarchar(50),
 @rateclass nvarchar(50),
 @starttime datetime,
 @deptime datetime,
 @updatetime datetime,
 @nights int,
 @room int,
 @guestfirstname nvarchar(50),
 @guestlastname nvarchar(50),
 @guestemail nvarchar(50),
 @guestphone nvarchar(50),
 @guestMP nvarchar(50),
 @guestaddressline1 nvarchar(50),
 @guestaddressline2 nvarchar(50),
 @guestcity nvarchar(50),
 @guestcountry nvarchar(50),
 @gueststate nvarchar(50),
 @guestzip nvarchar(50),
 @cctype nvarchar(50),
 @ccnumber nvarchar(50),
 @ccname nvarchar(50),
 @ccexpyear nvarchar(50),
 @ccexpmonth nvarchar(50),
 @frequentguestid nvarchar(50),
 @iata nvarchar(50),
 @remarks ntext,
 @confnum nvarchar(50),
 @cxlnum nvarchar(50),
 @status nvarchar(50),
 @propertyname nvarchar(500),
 @propertyname_e nvarchar(500),
 @totalmount nvarchar(50),
 @dailyprice nvarchar(500),
 @adults int,
 @children int,
 @plandesc varchar(500),
 @roomname varchar(500),
 @roomdesc varchar(500),
 @canclerule nvarchar(500),
 @guaranteerule nvarchar(500),
 @taxrule nvarchar(500),
 @incomingcall nvarchar(50),
 @fromurl nvarchar(255),
 @deleted int,
 @SubSource nvarchar(50),
 @lastuser nvarchar(50),
 @lastusertype nvarchar(50),
 @verifycode nvarchar(50),
 @getstatus int,
 @flgorder int,
 @departure datetime,
 @payment nvarchar(50),
 @fit_userid uniqueidentifier,
 @cxlrule as
nvarchar(500),
@guarule as nvarchar(500),
@payamount as nvarchar(50),
@currency as nvarchar(50)
as
insert into resvlog(userid, usertype,
 propertyid,roomtype,rateclass,starttime,deptime,updatetime,nights,room,guestfirstname,guestlastname,guestemail,guestphone,guestMP,guestaddressline1,guestaddressline2,guestcity,guestcountry,gueststate,guestzip,cctype,ccnumber,ccname,ccexpyear,ccexpmonth,frequentguestid,iata,remarks,confnum,cxlnum,status,propertyname,propertyname_e,totalmount,dailyprice,adults,children,plandesc,roomname,roomdesc,canclerule,guaranteerule,taxRule,incomingcall,fromurl,deleted,SubSource,lastuser,lastusertype,verifycode,getstatu
s,flgorder,departure,payment,fit_userid) values
                  
 (@userid,@usertype,@propertyid,@roomtype,@rateclass,@starttime,@deptime,@updatetime,@nights,@room,@guestfirstname,@guestlastname,@guestemail,@guestphone,@guestMP,@guestaddressline1,@guestaddressline2,@guestcity,@guestcountry,@gueststate,@guestzip,@cctype,@ccnumber,@ccname,@ccexpyear,@ccexpmonth,@frequentguestid,@iata,@remarks,@confnum,@cxlnum,@status,@propertyname,@propertyname_e,@totalmount,@dailyprice,@adults,@children,@plandesc,@roomname,@roomdesc,@canclerule,@guaranteerule,@taxrule,@incomingcall,@from
url,@deleted,@SubSource,@lastuser,@lastusertype,@verifycode,@getstatus,@flgorder,@departure,@payment,@fit_userid)
insert into pay ( confnum , paytimebegin , payamount , status , hotelname , hotelname_e , firstname , lastname , checkin , checkout , nights , plandesc , roomdesc , room , adult , children , totalmount , Cdescription , Gdescription , remark , Address1_e , Address1 , Phone , CancellationPolicy , GuaranteePolicy , currency )values
                 (                @verifycode , getdate(), @payamount , 0, @propertyname , @propertyname_e , @guestfirstname , @guestlastname ,convert(varchar(10), @starttime,120) ,convert(varchar(10),  @deptime,120) , @nights , @plandesc , @roomdesc , @room, @adults  , @children , @payamount , @canclerule , @guaranteerule , @remarks , @guestaddressline1 , @guestaddressline2 , @guestphone , @cxlrule , @guarule , @currency )
go


create procedure dbo.FIT_OverSeas_ResvLog_Add_Payment_Mod @userid int,
 @usertype nvarchar(50),
 @propertyid int,
 @roomtype nvarchar(50),
 @rateclass nvarchar(50),
 @starttime datetime,
 @deptime datetime,
 @updatetime datetime,
 @nights int,
 @room int,
 @guestfirstname nvarchar(50),
 @guestlastname nvarchar(50),
 @guestemail nvarchar(50),
 @guestphone nvarchar(50),
 @guestMP nvarchar(50),
 @guestaddressline1 nvarchar(50),
 @guestaddressline2 nvarchar(50),
 @guestcity nvarchar(50),
 @guestcountry nvarchar(50),
 @gueststate nvarchar(50),
 @guestzip nvarchar(50),
 @cctype nvarchar(50),
 @ccnumber nvarchar(50),
 @ccname nvarchar(50),
 @ccexpyear nvarchar(50),
 @ccexpmonth nvarchar(50),
 @frequentguestid nvarchar(50),
 @iata nvarchar(50),
 @remarks ntext,
 @confnum nvarchar(50),
 @cxlnum nvarchar(50),
 @status nvarchar(50),
 @propertyname nvarchar(500),
 @propertyname_e nvarchar(500),
 @totalmount nvarchar(50),
 @dailyprice nvarchar(500),
 @adults int,
 @children int,
 @plandesc varchar(500),
 @roomname varchar(500),
 @roomdesc varchar(500),
 @canclerule nvarchar(500),
 @guaranteerule nvarchar(500),
 @taxrule nvarchar(500),
 @incomingcall nvarchar(50),
 @fromurl nvarchar(255),
 @deleted int,
 @SubSource nvarchar(50),
 @lastuser nvarchar(50),
 @lastusertype nvarchar(50),
 @verifycode nvarchar(50),
 @getstatus int,
 @flgorder int,
 @departure datetime,
 @payment nvarchar(50),
 @fit_userid uniqueidentifier,
 @cxlrule as
nvarchar(500),
@guarule as nvarchar(500),
@payamount as nvarchar(50),
@currency as nvarchar(50)
as
update resvlog set
 userid=@userid,usertype=@usertype,
roomtype=@roomtype,rateclass=@rateclass,starttime=@starttime,
deptime=@deptime,updatetime=@updatetime,nights=@nights,room=@room,
guestfirstname=@guestfirstname,guestlastname=@guestlastname,
guestemail=@guestemail,guestphone=@guestphone,guestMP=@guestMP,
guestaddressline1=@guestaddressline1,guestaddressline2=@guestaddressline2,
guestcity=@guestcity,guestcountry=@guestcountry,
gueststate=@gueststate,guestzip=@guestzip,cctype=@cctype,
ccnumber=@ccnumber,ccname=@ccname,ccexpyear=@ccexpyear,
ccexpmonth=@ccexpmonth,frequentguestid=@frequentguestid,
iata=@iata,remarks=@remarks,confnum=@confnum,cxlnum=@cxlnum,
status=@status,propertyname=@propertyname,propertyname_e=@propertyname_e,
totalmount=@totalmount,dailyprice=@dailyprice,adults=@adults,
children=@children,plandesc=@plandesc,roomname=@roomname,
roomdesc=@roomdesc,canclerule=@canclerule,guaranteerule=@guaranteerule,
taxrule=@taxrule,incomingcall=@incomingcall,fromurl=@fromurl,deleted=@deleted,
SubSource=@SubSource,lastuser=@lastuser,lastusertype=@lastusertype,
getstatus=@getstatus,flgorder=@flgorder,departure=@departure,payment=@payment,
fit_userid=@fit_userid
where propertyid=@propertyid and verifycode=@verifycode;

update  pay set paytimebegin=getdate() , payamount=@payamount ,
hotelname=@propertyname , 
hotelname_e=@propertyname_e , firstname=@guestfirstname , lastname=@guestlastname , checkin=convert(varchar(10),@starttime,120) ,
 checkout=convert(varchar(10), @deptime,120), nights=@nights , plandesc=@plandesc , roomdesc=@roomdesc , room=@room , adult=@adults ,
 children=@children , totalmount=@payamount , Cdescription=@canclerule , Gdescription=@guaranteerule , remark=@remarks , 
Address1_e=@guestaddressline1 , Address1=@guestaddressline2 , Phone=@guestphone , CancellationPolicy=@cxlrule , GuaranteePolicy=@guarule , currency =@currency
where confnum=@verifycode ;
go


create procedure dbo.FIT_ResvLog_Add_Payment @userid int,
 @usertype nvarchar(50),
 @propertyid int,
 @roomtype nvarchar(50),
 @rateclass nvarchar(50),
 @starttime datetime,
 @deptime datetime,
 @updatetime datetime,
 @nights int,
 @room int,
 @guestfirstname nvarchar(50),
 @guestlastname nvarchar(50),
 @guestemail nvarchar(50),
 @guestphone nvarchar(50),
 @guestMP nvarchar(50),
 @guestaddressline1 nvarchar(50),
 @guestaddressline2 nvarchar(50),
 @guestcity nvarchar(50),
 @guestcountry nvarchar(50),
 @gueststate nvarchar(50),
 @guestzip nvarchar(50),
 @cctype nvarchar(50),
 @ccnumber nvarchar(50),
 @ccname nvarchar(50),
 @ccexpyear nvarchar(50),
 @ccexpmonth nvarchar(50),
 @frequentguestid nvarchar(50),
 @iata nvarchar(50),
 @remarks ntext,
 @confnum nvarchar(50),
 @cxlnum nvarchar(50),
 @status nvarchar(50),
 @propertyname nvarchar(500),
 @propertyname_e nvarchar(500),
 @totalmount nvarchar(50),
 @dailyprice nvarchar(500),
 @adults int,
 @children int,
 @plandesc varchar(500),
 @roomname varchar(500),
 @roomdesc varchar(500),
 @canclerule nvarchar(500),
 @guaranteerule nvarchar(500),
 @taxrule nvarchar(500),
 @incomingcall nvarchar(50),
 @fromurl nvarchar(255),
 @deleted int,
 @SubSource nvarchar(50),
 @lastuser nvarchar(50),
 @lastusertype nvarchar(50),
 @verifycode nvarchar(50),
 @getstatus int,
 @flgorder int,
 @departure datetime,
 @payment nvarchar(50),
 @fit_userid uniqueidentifier as
insert into
 resvlog(userid,usertype,propertyid,roomtype,rateclass,starttime,deptime,updatetime,nights,room,guestfirstname,guestlastname,guestemail,guestphone,guestMP,guestaddressline1,guestaddressline2,guestcity,guestcountry,gueststate,guestzip,cctype,ccnumber,ccname,ccexpyear,ccexpmonth,frequentguestid,iata,remarks,confnum,cxlnum,status,propertyname,propertyname_e,totalmount,dailyprice,adults,children,plandesc,roomname,roomdesc,canclerule,guaranteerule,taxRule,incomingcall,fromurl,deleted,SubSource,lastuser,lastuser
type,verifycode,getstatus,flgorder,departure,payment,fit_userid)
 values(@userid,@usertype,@propertyid,@roomtype,@rateclass,@starttime,@deptime,@updatetime,@nights,@room,@guestfirstname,@guestlastname,@guestemail,@guestphone,@guestMP,@guestaddressline1,@guestaddressline2,@guestcity,@guestcountry,@gueststate,@guestzip,@cctype,@ccnumber,@ccname,@ccexpyear,@ccexpmonth,@frequentguestid,@iata,@remarks,@confnum,@cxlnum,@status,@propertyname,@propertyname_e,@totalmount,@dailyprice,@adults,@children,@plandesc,@roomname,@roomdesc,@canclerule,@guaranteerule,@taxrule,@incomingcall
,@fromurl,@deleted,@SubSource,@lastuser,@lastusertype,@verifycode,@getstatus,@flgorder,@departure,@payment,@fit_userid)
go


create procedure dbo.FIT_ResvLog_Add_Payment_Card @userid int,
 @usertype nvarchar(50),
 @propertyid int,
 @roomtype nvarchar(50),
 @rateclass nvarchar(50),
 @starttime datetime,
 @deptime datetime,
 @updatetime datetime,
 @nights int,
 @room int,
 @guestfirstname nvarchar(50),
 @guestlastname nvarchar(50),
 @guestemail nvarchar(50),
 @guestphone nvarchar(50),
 @guestMP nvarchar(50),
 @guestaddressline1 nvarchar(50),
 @guestaddressline2 nvarchar(50),
 @guestcity nvarchar(50),
 @guestcountry nvarchar(50),
 @gueststate nvarchar(50),
 @guestzip nvarchar(50),
 @cctype nvarchar(50),
 @ccnumber nvarchar(50),
 @ccname nvarchar(50),
 @ccexpyear nvarchar(50),
 @ccexpmonth nvarchar(50),
 @frequentguestid nvarchar(50),
 @iata nvarchar(50),
 @remarks ntext,
 @confnum nvarchar(50),
 @cxlnum nvarchar(50),
 @status nvarchar(50),
 @propertyname nvarchar(500),
 @propertyname_e nvarchar(500),
 @totalmount nvarchar(50),
 @dailyprice nvarchar(500),
 @adults int,
 @children int,
 @plandesc varchar(500),
 @roomname varchar(500),
 @roomdesc varchar(500),
 @canclerule nvarchar(500),
 @guaranteerule nvarchar(500),
 @taxrule nvarchar(500),
 @incomingcall nvarchar(50),
 @fromurl nvarchar(255),
 @deleted int,
 @SubSource nvarchar(50),
 @lastuser nvarchar(50),
 @lastusertype nvarchar(50),
 @verifycode nvarchar(50),
 @getstatus int,
 @flgorder int,
 @departure datetime,
 @payment nvarchar(50),
 @fit_userid uniqueidentifier,
 @CardNO as
nvarchar(100),
@CRemark as nvarchar(100),
@MemberType as nvarchar(100),
@Corp_ID as int
as
insert into
 resvlog(userid,usertype,propertyid,roomtype,rateclass,starttime,deptime,updatetime,nights,room,guestfirstname,guestlastname,guestemail,guestphone,guestMP,guestaddressline1,guestaddressline2,guestcity,guestcountry,gueststate,guestzip,cctype,ccnumber,ccname,ccexpyear,ccexpmonth,frequentguestid,iata,remarks,confnum,cxlnum,status,propertyname,propertyname_e,totalmount,dailyprice,adults,children,plandesc,roomname,roomdesc,canclerule,guaranteerule,taxRule,incomingcall,fromurl,deleted,SubSource,lastuser,lastuser
type,verifycode,getstatus,flgorder,departure,payment,fit_userid)
 values(@userid,@usertype,@propertyid,@roomtype,@rateclass,@starttime,@deptime,@updatetime,@nights,@room,@guestfirstname,@guestlastname,@guestemail,@guestphone,@guestMP,@guestaddressline1,@guestaddressline2,@guestcity,@guestcountry,@gueststate,@guestzip,@cctype,@ccnumber,@ccname,@ccexpyear,@ccexpmonth,@frequentguestid,@iata,@remarks,@confnum,@cxlnum,@status,@propertyname,@propertyname_e,@totalmount,@dailyprice,@adults,@children,@plandesc,@roomname,@roomdesc,@canclerule,@guaranteerule,@taxrule,@incomingcall
,@fromurl,@deleted,@SubSource,@lastuser,@lastusertype,@verifycode,@getstatus,@flgorder,@departure,@payment,@fit_userid);
if @CardNO!=''
begin
insert into dbo.FIT_Card_Resvlog(Verifycode,CardNO,Remark,MemberType,UserID,Corp_ID,fit_userid)values
(@verifycode,@CardNO,@CRemark,@MemberType,@UserID,@Corp_ID,@fit_userid);
end
go


create procedure dbo.FIT_ResvLog_Sel @verifycode nvarchar(50) as
begin 
  select a.*,b.CardNO,b.Remark as CRemark from (select * from  resvlog where  verifycode=@verifycode)a left join FIT_Card_Resvlog b on a.verifycode=b.verifycode;
end
go


create procedure dbo.FIT_UserLog_GetIP @UserID as
uniqueidentifier
as 
begin
select top 2 * from FIT_UserLog where userID=@UserID order by LogNo desc
end
go


create procedure dbo.FIT_UserLog_Insert @UserID as
uniqueidentifier,@IP as varchar(20),@country as nvarchar(50),@city as nvarchar(50),@SessionID as varchar(100) 
as 
begin
Insert into FIT_UserLog(UserID,IP,country,city,SessionID)values(@UserID,@IP,@country,@city,@SessionID); 
end
go


create function dbo.GetCCCardName (@cctype as varchar(5))
returns nvarchar(100) 
as 
begin
declare @temp as varchar(100);
 if UPPER(@cctype)='VI'
  set @temp='Visa';
else if UPPER(@cctype)='MC'
  set @temp='American Express';
else if UPPER(@cctype)='AX'
  set @temp='';
else if UPPER(@cctype)='DC'
  set @temp='Diners Club';
else if UPPER(@cctype)='JC'
  set @temp='Japan Credit';
else 
  set @temp='';
return @temp;

end
go


create function dbo.GetCCCardNames (@cctype as varchar(200),@lan as varchar(2))
returns nvarchar(4000) 
as 
begin
declare @temp as varchar(4000);
if(@lan=0)
set @temp='现金';
else
set @temp='Cash;'
 if charindex('VI',UPPER(@cctype))>0
  set @temp=@temp+'Visa';
else if charindex('MC',UPPER(@cctype))>0
  set @temp=@temp+'MasterCard';
else if charindex('AX',UPPER(@cctype))>0
  set @temp=@temp+'American Express';
else if charindex('DC',UPPER(@cctype))>0
  set @temp=@temp+'Diners Club';
else if charindex('JC',UPPER(@cctype))>0
  set @temp=@temp+'Japan Credit';

return @temp;

end
go


create procedure dbo.GetCCMail @PageSize     int = 10,           
 @PageIndex    int = 1,            
 @strWhere     nvarchar(1000) = '',  
 @id int out as
declare @sql nvarchar(1000) 
declare @temp nvarchar(1000)

set @temp = 'select min(id) from (select top ' + str(@PageSize*(@PageIndex-1)+1) + ' m.id from cc_mail m inner join cc_resvproc r on r.otherid = m.id where r.proctype=100 or r.proctype=110 and r.confnum <> ' + '''''' + ' order by m.id desc) as a'
set @sql = 'select top ' + str(@PageSize) + ' rr.confnum confnums,mm.* from cc_mail mm inner join cc_resvproc rr on rr.otherid = mm.id where (rr.proctype=100 or rr.proctype=110) and rr.confnum <> ' + '''''' + ' and mm.id<=(' + @temp +')'

if @strWhere != ''
begin
   set @sql = @sql + ' and rr.confnum like ''%'  + @strWhere + '%'''
end

set @sql = @sql + ' order by rr.confnum desc'




exec (@sql) 

set @id= @@IDENTITY
return @id
go


create procedure dbo.GetChildUserInfo @Username nvarchar(50),
 @Userid nvarchar(50) as
declare @MyUsername nvarchar(50),
        @MyUserid nvarchar(50)
    
    set @Username=replace(@Username,'''','''''') 
    set @Username=replace(@Username,'--','') 
    set @Username=replace(@Username,';','') 
    set @Userid=replace(@Userid,'''','''''') 
    set @Userid=replace(@Userid,'--','') 
    set @Userid=replace(@Userid,';','') 
set @MyUsername =@Username
set  @MyUserid=@Userid
if(@Myusername<>'')
begin
  select * from [User] where parentid =(select parentid from [User] where username=@MyUsername)
   
end
else
begin
   select * from [User] where parentid =(select parentid from [User] where userid=@MyUserid)
end
go


create procedure dbo.GetFIT_Profile @ApplicationName      nvarchar(256),
 	@UserName             nvarchar(256),
 	@FirstName            nvarchar(100)        OUTPUT,
 	@LastName             nvarchar(100)        OUTPUT,
 	@MobilePhone          varchar(50)          OUTPUT,
 	@Phone                varchar(50)          OUTPUT,
 	@Address              nvarchar(200)        OUTPUT,
 	@LogTimes             int                  OUTPUT,
 	@LastIP               varchar(24)          OUTPUT as
declare	@ApplicationId uniqueidentifier
set		@ApplicationId = NULL

exec dbo.aspnet_Applications_CreateApplication @ApplicationName, @ApplicationId OUTPUT


select	@FirstName=FirstName,
	@LastName=LastName,
	@MobilePhone=MobilePhone,
	@Phone=Phone,
	@Address=Address,
	@LogTimes=LogTimes,
	@LastIP=LastIP	
from	dbo.FIT_Profile pt,
	    dbo.vw_aspnet_Users u
where	u.ApplicationId	= @ApplicationId
and		u.UserName		= @UserName
and		u.UserId		= pt.UserId
go


create procedure dbo.GetHotelInfo @Confnum nvarchar(50),
 @UserName nvarchar(50),
 @UserLevel nvarchar(50) as
declare @MyConfnum nvarchar(50),
        @UserID int
    
    set @Confnum=replace(@Confnum,'''','''''') 
    set @Confnum=replace(@Confnum,'--','') 
    set @Confnum=replace(@Confnum,';','') 
set @MyConfnum =@Confnum


SELECT [Hotel].*,[resvlog].* FROM [resvlog],[Hotel] where   [resvlog].confnum=@MyConfnum and  [resvlog].propertyid = [Hotel].pid
go


create procedure dbo.GetLogInfo @Confnum nvarchar(50) as
declare @MyConfnum nvarchar(50)
    
    set @Confnum=replace(@Confnum,'''','''''') 
    set @Confnum=replace(@Confnum,'--','') 
    set @Confnum=replace(@Confnum,';','') 
set @MyConfnum =@Confnum

select procType,otherID,Addtime from [CC_ResvProc] where confnum = @Confnum order by addtime desc
go


create function dbo.GetNotInID (@IDS varchar(1000))
returns varchar(1000)
as 
begin
declare @temp as varchar(1000);
set @temp='';
select @temp=@temp+convert(varchar,classID)+',' from HotelGroup where  charindex(','+convert(varchar,classID)+',',','+@IDS+',')=0
select @temp=left(@temp,len(@temp)-1);
return @temp;
end
go


create procedure dbo.GetPagingRecord ( 
         @tablename varchar(100),
         @fieldlist varchar(4000)='*',
         @orderfield varchar(100),
         @keyfield varchar(100),
         @pageindex int,
         @pagesize int=20,
         @strwhere varchar(4000)= null ,
         @ordertype bit=1
 	
     ) as
SET NOCOUNT ON 
    declare @sqlstr varchar(6000) 
    Declare @sql nvarchar(4000);
    declare @totalRecord int;
    
    set @strwhere=replace(@strwhere,'''','''''') 
    set @strwhere=replace(@strwhere,'--','') 
    set @strwhere=replace(@strwhere,';','') 
       
  
       
   
     
        

    
    
    set @sqlstr='declare @CurPageNum int;' 
    set @sqlstr=@sqlstr+'declare @nextpagenum int;' 
    set @sqlstr=@sqlstr+'set @curpagenum='+cast(@PageIndex as varchar)+'*'+cast(@Pagesize as varchar)+';' 
    set @sqlstr=@sqlstr+'set @nextpagenum='+cast(@PageIndex+1 as varchar)+'*'+cast(@Pagesize as varchar)+';' 
    set @sqlstr=@sqlstr+'declare @sqlstr varchar(6000);' 
    if @ordertype=1 
    begin 
    set @sqlstr=@sqlstr+'set @sqlstr=''select '+@fieldlist+' from ( select top ''+cast(@nextpagenum as varchar)+'' * from  
 
'+@tablename+'  where  '+@strwhere+' order by '+@orderfield+' desc ) as a where '+@keyfield+' not in (  
 
select top ''+cast(@curpagenum as varchar)+'' '+@keyfield+' from '+@tablename+' where '+@strwhere+'  
 
order by '+@orderfield+' desc) order by '+@orderfield+' desc'';' 
    end 
    else 
    begin 
    set @sqlstr=@sqlstr+'set @sqlstr=''select '+@fieldlist+' from ( select top ''+cast(@nextpagenum as varchar)+'' * from  
 
'+@tablename+'  where '+@strwhere+' order by '+@orderfield+' asc ) as a where '+@keyfield+' not in (  
 
select top ''+cast(@curpagenum as varchar)+'' '+@keyfield+' from '+@tablename+' where '+@strwhere+'  
 
order by '+@orderfield+' asc) order by '+@orderfield+' asc'';' 
    end 
     
    set @sqlstr=@sqlstr+'execute( @sqlstr)' 
    execute(@sqlstr)
    print @sqlstr
go


create procedure dbo.GetPlanCode @PID nvarchar(4000),
 @PriceRange nvarchar(50),
 @CheckIn datetime,
 @CheckOut datetime,
 @RateCode nvarchar(4000), 
 @languagetype int =0 as
declare @stemp varchar(6000) 
if(@languagetype=0)
begin
set @stemp ='SELECT DISTINCT c.plancode,c.Property_id,p.plandesc,p.roomdesc,p.roomname,AddBed,Net,Nosmoke  FROM H_cache as c left join h_plan as p on  c.property_id=p.property_id and c.plancode=p.plancode and p.languagetype=0'
end
if(@languagetype=1)
begin
set @stemp ='SELECT DISTINCT c.plancode,c.Property_id,p.plandesc,p.roomdesc,p.roomname,AddBed,Net,Nosmoke   FROM H_cache as c left join h_plan as p on  c.property_id=p.property_id and c.plancode=p.plancode and p.languagetype=1'
end


set @stemp =@stemp+ ' WHERE (c.Property_id IN ('+@PID+') and  '

if (@PriceRange!='')
begin
	declare @MyPriceRange nvarchar(100)

	if (@PriceRange='<=250')
	set @MyPriceRange ='(c.priceNoTax>0 and c.priceNoTax<= 250)'
	if (@PriceRange='250-400')
	set @MyPriceRange ='(c.priceNoTax>250 and c.priceNoTax<=400)'
	if (@PriceRange='400-600')
	set @MyPriceRange ='(c.priceNoTax>400 and c.priceNoTax<=600)'
	if (@PriceRange='600-800')
	set @MyPriceRange ='(c.priceNoTax>600 and c.priceNoTax<=800)'
	if (@PriceRange='>800')
	set @MyPriceRange ='c.priceNoTax> 800'

	set @stemp =@stemp +@MyPriceRange+' '
	
end
else
begin
set @stemp =@stemp+ '  c.priceNoTax>0 '
end

set @stemp =@stemp+ '  and c.avstat!=''N''  and (( datediff(hh,getdate(),c.Availdate)+24>=c.cutoff )  and  c.Availdate>= '''+convert(varchar(10),@CheckIn,120)+''' AND c.Availdate<'''+convert(varchar(10),@CheckOut,120)+''') '




if (@RateCode !='')
begin
set @stemp =@stemp+' and '+  @RateCode
end

set @stemp =@stemp+' ) '


print @stemp
exec ( @stemp )
go


create procedure dbo.GetPlanCodeDFBCO @PID nvarchar(4000),
 @PriceRange nvarchar(50),
 @CheckIn datetime,
 @CheckOut datetime,
 @RateCode nvarchar(4000), 
 @languagetype int =1 as
declare @stemp varchar(6000) 
if(@languagetype=0)
begin
set @stemp ='SELECT DISTINCT c.plancode,c.Property_id,p.plandesc,p.roomdesc,p.roomname  FROM H_cache as c left join h_plan as p on  c.property_id=p.property_id and c.plancode=p.plancode and p.languagetype=0'
end
if(@languagetype=1)
begin
set @stemp ='SELECT DISTINCT c.plancode,c.Property_id,p.plandesc,p.roomdesc,p.roomname  FROM H_cache as c left join h_plan as p on  c.property_id=p.property_id and c.plancode=p.plancode and p.languagetype=1'
end


set @stemp =@stemp+ ' WHERE (c.Property_id IN ('+@PID+') and  '

if (@PriceRange!='')
begin
	declare @MyPriceRange nvarchar(100)

	if (@PriceRange='<=250')
	set @MyPriceRange ='(c.priceNoTax>0 and c.priceNoTax<= 250)'
	if (@PriceRange='250-400')
	set @MyPriceRange ='(c.priceNoTax>250 and c.priceNoTax<=400)'
	if (@PriceRange='400-600')
	set @MyPriceRange ='(c.priceNoTax>400 and c.priceNoTax<=600)'
	if (@PriceRange='600-800')
	set @MyPriceRange ='(c.priceNoTax>600 and c.priceNoTax<=800)'
	if (@PriceRange='>800')
	set @MyPriceRange ='c.priceNoTax> 800'

	set @stemp =@stemp +@MyPriceRange+' '
	
end
else
begin
set @stemp =@stemp+ '  c.priceNoTax>0 '
end

set @stemp =@stemp+ '  and c.avstat!=''N''  and (( datediff(hh,getdate(),c.Availdate)+24>=c.cutoff )  and  c.Availdate>= '''+convert(varchar(10),@CheckIn,120)+''' AND c.Availdate<'''+convert(varchar(10),@CheckOut,120)+''') '




if (@RateCode !='')
begin
set @stemp =@stemp+' and '+  @RateCode
end

set @stemp =@stemp+' ) '



exec ( @stemp )
go


create procedure dbo.GetPlanCodeNew @PID nvarchar(4000),
 @PriceRange nvarchar(50),
 @CheckIn datetime,
 @CheckOut datetime,
 @RateCode nvarchar(4000), 
 @languagetype int =0 as
declare @stemp varchar(6000) 
if(@languagetype=0)
begin
set @stemp ='SELECT  distinct Availdate,c.Allotment,c.MaxLos,c.MinLos,c.gua, c.PriceNoTax,c.AvStat,c.RateCode,c.RoomCode,c.Property_id,p.plandesc,p.roomdesc,p.roomname,p.planname  FROM H_cache as c left join h_plan as p on  c.property_id=p.property_id and c.plancode=p.plancode and p.languagetype=0'
end
if(@languagetype=1)
begin
set @stemp ='SELECT  distinct Availdate, c.Allotment,c.MaxLos,c.MinLos,c.gua,c.PriceNoTax,c.AvStat,c.RateCode,c.RoomCode,c.Property_id,p.plandesc,p.roomdesc,p.roomname,p.planname  FROM H_cache as c left join h_plan as p on  c.property_id=p.property_id and c.plancode=p.plancode and p.languagetype=1'
end


set @stemp =@stemp+ ' WHERE (c.Property_id IN ('+@PID+') and  '

if (@PriceRange!='')
begin
	declare @MyPriceRange nvarchar(100)

	if (@PriceRange='<=250')
	set @MyPriceRange ='(c.priceNoTax>0 and c.priceNoTax<= 250)'
	if (@PriceRange='250-400')
	set @MyPriceRange ='(c.priceNoTax>250 and c.priceNoTax<=400)'
	if (@PriceRange='400-600')
	set @MyPriceRange ='(c.priceNoTax>400 and c.priceNoTax<=600)'
	if (@PriceRange='600-800')
	set @MyPriceRange ='(c.priceNoTax>600 and c.priceNoTax<=800)'
	if (@PriceRange='>800')
	set @MyPriceRange ='c.priceNoTax> 800'

	set @stemp =@stemp +@MyPriceRange+' '
	
end
else
begin
set @stemp =@stemp+ '  c.priceNoTax>0 '
end

set @stemp =@stemp+ '  and c.avstat!=''N''  and (( datediff(hh,getdate(),c.Availdate)+24>=c.cutoff )  and  c.Availdate>= '''+convert(varchar(10),@CheckIn,120)+''' AND c.Availdate<'''+convert(varchar(10),@CheckOut,120)+''')' 




if (@RateCode !='')
begin
set @stemp =@stemp+' and '+  @RateCode
end

set @stemp =@stemp+' )  order by Availdate,RateCode'

print @stemp
exec ( @stemp )
go


create procedure dbo.GetPlanCodePrice @PID nvarchar(4000),
 @PriceRange nvarchar(50),
 @CheckIn datetime,
 @CheckOut datetime,
 @RateCode nvarchar(4000), 
 @languagetype int =0 as
declare @stemp varchar(6000) 
if(@languagetype=0)
begin
set @stemp ='SELECT DISTINCT c.Allotment,c.MaxLos,c.MinLos,c.gua, c.PriceNoTax,c.AvStat,c.RateCode,c.RoomCode,c.Property_id,p.plandesc,p.roomdesc,p.roomname,p.planname  FROM H_cache as c left join h_plan as p on  c.property_id=p.property_id and c.plancode=p.plancode and p.languagetype=0'
end
if(@languagetype=1)
begin
set @stemp ='SELECT DISTINCT  c.Allotment,c.MaxLos,c.MinLos,c.gua,c.PriceNoTax,c.AvStat,c.RateCode,c.RoomCode,c.Property_id,p.plandesc,p.roomdesc,p.roomname,p.planname  FROM H_cache as c left join h_plan as p on  c.property_id=p.property_id and c.plancode=p.plancode and p.languagetype=1'
end


set @stemp =@stemp+ ' WHERE (c.Property_id IN ('+@PID+') and  '

if (@PriceRange!='')
begin
	declare @MyPriceRange nvarchar(100)

	if (@PriceRange='<=250')
	set @MyPriceRange ='(c.priceNoTax>0 and c.priceNoTax<= 250)'
	if (@PriceRange='250-400')
	set @MyPriceRange ='(c.priceNoTax>250 and c.priceNoTax<=400)'
	if (@PriceRange='400-600')
	set @MyPriceRange ='(c.priceNoTax>400 and c.priceNoTax<=600)'
	if (@PriceRange='600-800')
	set @MyPriceRange ='(c.priceNoTax>600 and c.priceNoTax<=800)'
	if (@PriceRange='>800')
	set @MyPriceRange ='c.priceNoTax> 800'

	set @stemp =@stemp +@MyPriceRange+' '
	
end
else
begin
set @stemp =@stemp+ '  c.priceNoTax>0 '
end

set @stemp =@stemp+ '  and c.avstat!=''N''  and (( datediff(hh,getdate(),c.Availdate)+24>=c.cutoff )  and  c.Availdate>= '''+convert(varchar(10),@CheckIn,120)+''' AND c.Availdate<'''+convert(varchar(10),@CheckOut,120)+''') '




if (@RateCode !='')
begin
set @stemp =@stemp+' and '+  @RateCode
end

set @stemp =@stemp+' ) '


print @stemp
exec ( @stemp )
go


create procedure dbo.GetPlanRate @PIDCode varchar(8000),
 @CheckIn datetime,
 @CheckOut datetime as
declare @stemp varchar(8000) 

set @stemp ='SELECT plancode,ratecode,roomcode,avstat,minlos,maxlos,gua,cxl,cutoff, Property_id, priceNoTax, [ID],Allotment,Availdate FROM H_cache  '



if (@PIDCode !='')
begin
set @stemp =@stemp+ ' WHERE  '+ @PIDCode 
end
else 
begin
set @stemp =@stemp+ ' WHERE 1=2  '
end

set @stemp =@stemp+ ' and  ( Availdate>= '''+convert(varchar(10),@CheckIn,120)+''' AND Availdate<'''+convert(varchar(10),@CheckOut,120)+''')  order by plancode, availdate '
print @stemp
exec ( @stemp )
go


create procedure dbo.GetPlanRatetemp @Pids nvarchar(4000),
 @PIDCode nvarchar(4000),
 @CheckIn datetime,
 @CheckOut datetime as
declare @stemp varchar(8000) 

set @stemp='
select  plancode,ratecode,roomcode,avstat,minlos,maxlos,gua,cxl,cutoff, Property_id, priceNoTax, [ID],Allotment,Availdate,pidcode,CurrencyCode,BreakfastNum,BreakfastPay,BroadBand  from (
SELECT plancode,ratecode,roomcode,avstat,minlos,maxlos,gua,cxl,cutoff, Property_id, priceNoTax, [ID],Allotment,Availdate,replace(str(property_id),'' '','''')+plancode as pidcode,CurrencyCode,BreakfastNum,BreakfastPay,BroadBand 
FROM H_cache
where ( Availdate>= '''+convert(varchar(10),@CheckIn,120)+''' AND Availdate<'''+convert(varchar(10),@CheckOut,120)+''') and property_id in ('+@Pids+')
) as a
where a.pidcode in ('+@PIDCode+') order by a.plancode,a.availdate'

print(@stemp)
exec(@stemp)
go


create procedure dbo.GetRecordByPage @tblName      varchar(255),       
     @fldName      varchar(255),       
     @PageSize     int = 10,           
     @PageIndex    int = 1,            
     @IsReCount    bit = 0,            
     @OrderType    bit = 0,            
     @strWhere     nvarchar(1000) = ''  
declare @strSQL   varchar(6000)       
declare @strTmp   varchar(100)        
declare @strOrder varchar(400)        

if @OrderType != 0
begin
    set @strTmp = '<(select min'
    set @strOrder = ' order by [' + @fldName +'] desc'
end
else
begin
    set @strTmp = '>(select max'
    set @strOrder = ' order by [' + @fldName +'] asc'
end

set @strSQL = 'select top ' + str(@PageSize) + ' * from ['
    + @tblName + '] where [' + @fldName + ']' + @strTmp + '(['
    + @fldName + ']) from (select top ' + str((@PageIndex-1)*@PageSize) + ' ['
    + @fldName + '] from [' + @tblName + ']' + @strOrder + ') as tblTmp)'
    + @strOrder

if @strWhere != ''
    set @strSQL = 'select top ' + str(@PageSize) + ' * from ['
        + @tblName + '] where [' + @fldName + ']' + @strTmp + '(['
        + @fldName + ']) from (select top ' + str((@PageIndex-1)*@PageSize) + ' ['
        + @fldName + '] from [' + @tblName + '] where ' + @strWhere + ' '
        + @strOrder + ') as tblTmp) and ' + @strWhere + ' ' + @strOrder

if @PageIndex = 1
begin
    set @strTmp =''
    if @strWhere != ''
        set @strTmp = ' where ' + @strWhere

    set @strSQL = 'select top ' + str(@PageSize) + ' * from ['
        + @tblName + ']' + @strTmp + ' ' + @strOrder
end

if @IsReCount != 0
    set @strSQL = 'select count(*) as Total from [' + @tblName + ']'+' where ' + @strWhere

exec (@strSQL)
go


create procedure dbo.GetResv @Confnum nvarchar(50) as
declare @MyConfnum nvarchar(50)
    
    set @Confnum=replace(@Confnum,'''','''''') 
    set @Confnum=replace(@Confnum,'--','') 
    set @Confnum=replace(@Confnum,';','') 
set @MyConfnum =@Confnum


SELECT * FROM [resvlog] where  confnum=@MyConfnum
go


create procedure dbo.GetResvAll @Confnum nvarchar(50) as
declare @MyConfnum nvarchar(50)
    
    set @Confnum=replace(@Confnum,'''','''''') 
    set @Confnum=replace(@Confnum,'--','') 
    set @Confnum=replace(@Confnum,';','') 
set @MyConfnum =@Confnum


SELECT resvlog.*,hotel.phone,hotel.address1,hotel.address1_e,hotel.checkin,hotel.checkout FROM [resvlog],[hotel] 
where  confnum=@MyConfnum and (resvlog.propertyid=hotel.pid or resvlog.propertyid=hotel.pid_e)
order by resvlog.id desc
go


create procedure dbo.GetResvAll_Booking @Confnum nvarchar(50),
 @lastname nvarchar(50) as
declare @MyConfnum nvarchar(50)
declare @MyLastname nvarchar(50)
    
    set @Confnum=replace(@Confnum,'''','''''') 
    set @Confnum=replace(@Confnum,'--','') 
    set @Confnum=replace(@Confnum,';','') 
    set @lastname=replace(@lastname,'''','''''') 
    set @lastname=replace(@lastname,'--','') 
    set @lastname=replace(@lastname,';','') 
set @MyConfnum =@Confnum
set    @Mylastname=@lastname

SELECT resvlog.*,hotel.phone,hotel.address1,hotel.address1_e,hotel.checkin,hotel.checkout FROM [resvlog],[hotel] where  confnum=@MyConfnum  and guestlastname=@lastname and (resvlog.propertyid=hotel.pid or resvlog.propertyid=hotel.pid_e)
go


create procedure dbo.GetResvConfnum @Confnum nvarchar(50),
 @UserName nvarchar(50),
 @UserLevel nvarchar(50) as
declare @MyConfnum nvarchar(50),
        @UserID int
    
    set @Confnum=replace(@Confnum,'''','''''') 
    set @Confnum=replace(@Confnum,'--','') 
    set @Confnum=replace(@Confnum,';','') 
set @MyConfnum =@Confnum



















SELECT * FROM [resvlog] where  confnum=@MyConfnum 
go


create procedure dbo.GetTaInfo @Confnum nvarchar(50),
 @UserName nvarchar(50),
 @UserLevel nvarchar(50) as
declare @MyConfnum nvarchar(50),
        @UserID int
    
    set @Confnum=replace(@Confnum,'''','''''') 
    set @Confnum=replace(@Confnum,'--','') 
    set @Confnum=replace(@Confnum,';','') 
set @MyConfnum =@Confnum


SELECT [Corp].*,[resvlog].* FROM [resvlog],[Corp] where   [resvlog].confnum=@MyConfnum and  [resvlog].iata = [Corp].IATA
go


create procedure dbo.GetUserInfo @Username nvarchar(50) as
declare @MyUsername nvarchar(50)
    
    set @Username=replace(@Username,'''','''''') 
    set @Username=replace(@Username,'--','') 
    set @Username=replace(@Username,';','') 
set @MyUsername =@Username


SELECT [USER].*, Corp.Corp_Id,Corp.corp_name, Corp.corp_name_e, corp.defaultrate, corp.IATA,corp.fax,corp.sendfax, corp.credit,corp.HotelGroupID,corp.corp_ID,corp.account,corp.accounttel,corp.accountfax,corp.accountemail,corp.business,corp.bsntel,corp.bsnfax,corp.bsnemail,corp.resvcredit,corp.NoHotelGroup  FROM [USER],[Corp] where  [USER].parentid = corp.corp_id and [USER].UserName=@MyUsername
go


create procedure dbo.GetUserInfo_ParentId @Parentid nvarchar(50) as
declare @Myparentid nvarchar(50)
    
    set @Parentid=replace(@Parentid,'''','''''') 
    set @Parentid=replace(@Parentid,'--','') 
    set @Parentid=replace(@Parentid,';','') 
set @Myparentid =@Parentid


SELECT [USER].*, Corp.corp_name, Corp.corp_name_e, corp.defaultrate, corp.IATA,corp.fax,corp.sendfax, corp.credit,corp.HotelGroupID,corp.corp_ID FROM [USER],[Corp] where  [USER].parentid = corp.corp_id and [USER].parentid=@Myparentid
go


create procedure dbo.GetUserInfo_UserID @userid nvarchar(50) as
declare @Myuserid nvarchar(50)
    
    set @userid=replace(@userid,'''','''''') 
    set @userid=replace(@userid,'--','') 
    set @userid=replace(@userid,';','') 
set @Myuserid =@userid


SELECT [USER].*, Corp.corp_name, Corp.corp_name_e, corp.defaultrate, corp.IATA,corp.fax,corp.sendfax, corp.credit,corp.HotelGroupID,corp.corp_ID FROM [USER],[Corp] where  [USER].parentid = corp.corp_id and [USER].userid=@Myuserid
go


create procedure dbo.Get_FIT_HotelComment_List @property_id as
int
as 


select  Score,Comment,left(IpAddress, len(IpAddress)- CharIndex('.',REVERSE(IpAddress))+1)+'***' as IP,Intime   from FIT_HotelComment where property_id=@property_id
go


create procedure dbo.Get_FIT_HotelComment_Result @property_id as
int
as 
declare @Count as int,@sum as decimal(18,2); 
select @Count=count(*),@sum=sum(score)   from FIT_HotelComment where property_id=@property_id
set @sum=convert(decimal(18,2),Convert(decimal(18,2),@sum)/Convert(decimal(18,2),@count));
if @Count=0 
select ''
else
select convert(varchar(10),@sum)+'|'+convert(varchar,@count)
go


create procedure dbo.Get_FIT_MobileValidate @MobileNo as
varchar(11),@validateCode as varchar(20),@IPAddress as varchar(24),@SessionID as varchar(200)
 as 
   update FIT_MobileValidate set RTimes=RTimes+1 where  MobileNo=@MobileNo and  validateCode = @validateCode  and   MobileNo=@MobileNo and   SessionID=@SessionID;
   select @@rowcount as r
go


create procedure dbo.Get_TA_CorpHotelPrice @username as
varchar(50),@checkin as varchar(10),@checkout as varchar(10),@CityID as int,@CommercialID as int,@DistrictID as int,@Stars as int,@Title as varchar(50),@GroupID as int,@minPrice as int,@maxPrice as int
as 
begin















declare @strArea as varchar(50);
if @CommercialID>0
   set @strArea='and   CommercialID='+convert(varchar,@CommercialID)+' '
else if @DistrictID>0
   set @strArea='and   DistrictID='+convert(varchar,@DistrictID)+' '
else if @CityID>0
   set  @strArea='and   CityID='+convert(varchar,@CityID)+' '
else
   set @strArea='';

declare @strStars as varchar(50);
if @stars=0
  set @strStars=' and ( stars=0 and  Diamond=0  ) '
else if @Stars<10 
  set @strStars='and ( stars='+convert(varchar,@Stars)+' or  Diamond='+convert(varchar,@Stars)+'  ) ';
else
 set  @strStars='';

declare @strKey as varchar(200);

set @Title=replace(@Title,'''','''''')
set @strkey='';
 if len(@Title)>0
  set  @strkey=' and(  title_e like ''%'+@Title+'%'' or  title like ''%'+@Title+'%'' or keywords like ''%'+@Title+'%''  )  '

declare @strprice as varchar(200)
if  @minprice=0 and @maxprice=0
    set @strprice='';
else if @minprice=@maxprice and @minprice>800
   set @strprice =' and a.priceNoTax> 800'
else
   set @strprice=' and (a.priceNoTax>'+Convert(varchar,@minprice)+' and a.priceNoTax<= '+Convert(varchar,@maxprice)+')'

declare @defaultRate as varchar(255),@hotelGroupid as  varchar(500),@CustomHotel as varchar(4000)
select 
@defaultRate=defaultRate,
@hotelGroupid=hotelGroupid,
@CustomHotel=CustomHotel  
from corp where Corp_id in(select parentid from [User] where  UserName like @username)

if    @defaultRate is null
         begin
          set @defaultRate='*****'
        end
else 
         begin
        if left(@defaultRate,1)=','
         begin
           set @defaultRate=right(@defaultRate,len(@defaultRate)-1);
         end
        
        if right(@defaultRate,1)=','
         begin
           set @defaultRate=left(@defaultRate,len(@defaultRate)-1);
         end
        
        set @defaultRate=''''+replace(@defaultRate,',',''',''')+'''';
        end

        if @GroupID=0 
        begin
                if left(@hotelGroupid,1)=','
                 begin
                   set @hotelGroupid=right(@hotelGroupid,len(@hotelGroupid)-1);
                 end
                
                if right(@hotelGroupid,1)=','
                 begin
                   set @hotelGroupid=left(@hotelGroupid,len(@hotelGroupid)-1);
                 end
                if len(@hotelGroupid)=0 or @hotelGroupid is null
                  begin
                   set @hotelGroupid=0;
                  end
        end
        else
        begin
          set @hotelGroupid=@GroupID;
        end

if left(@CustomHotel,1)=','
 begin
   set @CustomHotel=right(@CustomHotel,len(@CustomHotel)-1);
 end

if right(@CustomHotel,1)=','
 begin
   set @CustomHotel=left(@CustomHotel,len(@CustomHotel)-1);
 end
if len(@CustomHotel)=0 or @CustomHotel is null
  begin
   set @CustomHotel=0;
 end

declare @temp as varchar(8000)

set @temp='select DDay into #datetable from datetable where DDay>='''+@checkin+''' and  DDay<'''+@checkout+''' ;
select pid,title+(case  when ServiceCharge=1 then ''<br>(此酒店所有房型需另加１５％服务费)'' else '''' end) as title into #hotel from hotel where  1=1  '+@strKey+'  '+@strstars+' '+@strArea+'
and  Groupid in('+@hotelGroupid+') 
and Hotel_ID in ('+@CustomHotel+') ;
select  property_id,Plancode,languagetype,max(RoomName) as RoomName into #H_Plan from H_Plan group by property_id,Plancode,languagetype
 select  b.property_id,b.Plancode,c.title, b.RoomName,a.Availdate,a.PriceNoTax into #H_Cache  from 
 H_Cache a inner join  #H_Plan b on a.property_id=b.property_id and a.plancode=b.plancode and b.languagetype=0 
and (a.Availdate>='''+@checkin+''' and  a.Availdate<'''+@checkout+''') '+@strprice+'  
and a.ratecode in('+@defaultRate+')
inner join #hotel c on   a.property_id=c.pid  ;
select distinct property_id,Plancode,title,RoomName into #Plancode from #H_Cache;
select  property_id,title,count(*) as [rows] from #Plancode group by property_id,title;
select   property_id,Plancode,RoomName from #Plancode;
select  a.property_id,a.Plancode, convert(varchar(10),a.DDay,20) as Availdate,
case b.PriceNoTax when 0 then null else PriceNoTax end as PriceNoTax from 
(select a.DDay,b.property_id,b.Plancode,b.title, b.RoomName from  #datetable a,#plancode b)a left join
#H_Cache b on  a.Plancode=b.Plancode and  a.DDay=b.Availdate and a.property_id=b.property_id 
 order by  a.property_id,a.plancode,b.Availdate;
drop table #datetable;drop table #H_Plan;drop table #plancode;drop table #H_Cache;';

exec (@temp);

end
go


create procedure dbo.Get_TA_CorpHotelPrice_e @username as
varchar(50),@checkin as varchar(10),@checkout as varchar(10),@CityID as int,@CommercialID as int,@DistrictID as int,@Stars as int,@Title as varchar(50),@GroupID as int,@minPrice as int,@maxPrice as int
as 
begin















declare @strArea as varchar(50);
if @CommercialID>0
   set @strArea='and   CommercialID='+convert(varchar,@CommercialID)+' '
else if @DistrictID>0
   set @strArea='and   DistrictID='+convert(varchar,@DistrictID)+' '
else if @CityID>0
   set  @strArea='and   CityID='+convert(varchar,@CityID)+' '
else
   set @strArea='';

declare @strStars as varchar(50);
if @Stars<10 
  set @strStars='and ( stars='+convert(varchar,@Stars)+' or  Diamond='+convert(varchar,@Stars)+'  ) ';
else
 set  @strStars='';

declare @strKey as varchar(200);

set @Title=replace(@Title,'''','''''')
set @strkey='';
 if len(@Title)>0
  set  @strkey=' and(  title_e like ''%'+@Title+'%'' or  title like ''%'+@Title+'%'' or keywords like ''%'+@Title+'%''  )  '

declare @strprice as varchar(200)
if  @minprice=0 and @maxprice=0
    set @strprice='';
else if @minprice=@maxprice and @minprice>800
   set @strprice =' and a.priceNoTax> 800'
else
   set @strprice=' and (a.priceNoTax>'+Convert(varchar,@minprice)+' and a.priceNoTax<= '+Convert(varchar,@maxprice)+')'

declare @defaultRate as varchar(255),@hotelGroupid as  varchar(500),@CustomHotel as varchar(4000)
select 
@defaultRate=defaultRate,
@hotelGroupid=hotelGroupid,
@CustomHotel=CustomHotel  
from corp where Corp_id in(select parentid from [User] where  UserName like @username)

if    @defaultRate is null
         begin
          set @defaultRate='*****'
        end
else 
         begin
        if left(@defaultRate,1)=','
         begin
           set @defaultRate=right(@defaultRate,len(@defaultRate)-1);
         end
        
        if right(@defaultRate,1)=','
         begin
           set @defaultRate=left(@defaultRate,len(@defaultRate)-1);
         end
        
        set @defaultRate=''''+replace(@defaultRate,',',''',''')+'''';
        end

        if @GroupID=0 
        begin
                if left(@hotelGroupid,1)=','
                 begin
                   set @hotelGroupid=right(@hotelGroupid,len(@hotelGroupid)-1);
                 end
                
                if right(@hotelGroupid,1)=','
                 begin
                   set @hotelGroupid=left(@hotelGroupid,len(@hotelGroupid)-1);
                 end
                if len(@hotelGroupid)=0 or @hotelGroupid is null
                  begin
                   set @hotelGroupid=0;
                  end
        end
        else
        begin
          set @hotelGroupid=@GroupID;
        end

if left(@CustomHotel,1)=','
 begin
   set @CustomHotel=right(@CustomHotel,len(@CustomHotel)-1);
 end

if right(@CustomHotel,1)=','
 begin
   set @CustomHotel=left(@CustomHotel,len(@CustomHotel)-1);
 end
if len(@CustomHotel)=0 or @CustomHotel is null
  begin
   set @CustomHotel=0;
 end

declare @temp as varchar(8000)

set @temp='select DDay into #datetable from datetable where DDay>='''+@checkin+''' and  DDay<'''+@checkout+''' ;
select pid,title_e+(case  when ServiceCharge=1 then ''<br>(All this hotel rooms to be subject to 15% service charge)'' else '''' end) as title into #hotel from hotel where  1=1  '+@strKey+'  '+@strstars+' '+@strArea+'
and  Groupid in('+@hotelGroupid+') 
and Hotel_ID in ('+@CustomHotel+') ;
select  property_id,Plancode,languagetype,max(RoomName) as RoomName into #H_Plan from H_Plan group by property_id,Plancode,languagetype
 select  b.property_id,b.Plancode,c.title, b.RoomName,a.Availdate,a.PriceNoTax into #H_Cache  from 
 H_Cache a inner join  #H_Plan b on a.property_id=b.property_id and a.plancode=b.plancode and b.languagetype=1 
and (a.Availdate>='''+@checkin+''' and  a.Availdate<'''+@checkout+''') '+@strprice+'  
and a.ratecode in('+@defaultRate+')
inner join #hotel c on   a.property_id=c.pid  ;
select distinct property_id,Plancode,title,RoomName into #Plancode from #H_Cache;
select  property_id,title,count(*) as [rows] from #Plancode group by property_id,title;
select   property_id,Plancode,RoomName from #Plancode;
select  a.property_id,a.Plancode, convert(varchar(10),a.DDay,20) as Availdate,
case b.PriceNoTax when 0 then null else PriceNoTax end as PriceNoTax from 
(select a.DDay,b.property_id,b.Plancode,b.title, b.RoomName from  #datetable a,#plancode b)a left join
#H_Cache b on  a.Plancode=b.Plancode and  a.DDay=b.Availdate and a.property_id=b.property_id 
 order by  a.property_id,a.plancode,b.Availdate;
drop table #datetable;drop table #H_Plan;drop table #plancode;drop table #H_Cache;';

exec (@temp);

end
go


create procedure dbo.HFG_GetEmailIsValidateCode @gid as
int ,@uid as int,@checkcode as varchar(50),@hours as int
as 
if @hours<0
set @hours=10;
select @uid=uid from hfg_user where   getdate()<DATEADD(hh,@hours,Checkcodedate) and usercheckcode = @checkcode and uid =@uid and  gid=@gid
 if(@@rowcount>0)
   begin
               update hfg_user set emailcheck=1,Checkcodedate=getdate(),usercheckcode='' where uid=@uid;
               select 1 as pass;   
   end 
  else
      begin
                select 0 as pass   
      end
go


create procedure dbo.HFG_GetPagingRecord ( 
         @tablename varchar(100),
         @fieldlist varchar(4000)='*',
         @orderfield varchar(100),
         @keyfield varchar(100),
         @pageindex int,
         @pagesize int=20,
         @strwhere varchar(4000)= null ,
         @ordertype bit=1
 	
     ) as
SET NOCOUNT ON 
    declare @sqlstr varchar(6000) 
    Declare @sql nvarchar(4000);
    declare @totalRecord int;
    
    set @strwhere=replace(@strwhere,'''','''''') 
    set @strwhere=replace(@strwhere,'--','') 
    set @strwhere=replace(@strwhere,';','') 
       
  
       
   
     
        

    
    
    set @sqlstr='declare @CurPageNum int;' 
    set @sqlstr=@sqlstr+'declare @nextpagenum int;' 
    set @sqlstr=@sqlstr+'set @curpagenum='+cast(@PageIndex as varchar)+'*'+cast(@Pagesize as varchar)+';' 
    set @sqlstr=@sqlstr+'set @nextpagenum='+cast(@PageIndex+1 as varchar)+'*'+cast(@Pagesize as varchar)+';' 
    set @sqlstr=@sqlstr+'declare @sqlstr varchar(6000);' 
    if @ordertype=1 
    begin 
    set @sqlstr=@sqlstr+'set @sqlstr=''select '+@fieldlist+' from ( select top ''+cast(@nextpagenum as varchar)+'' * from  
 
'+@tablename+'  where  '+@strwhere+' order by '+@orderfield+' desc ) as a where '+@keyfield+' not in (  
 
select top ''+cast(@curpagenum as varchar)+'' '+@keyfield+' from '+@tablename+' where '+@strwhere+'  
 
order by '+@orderfield+' desc) order by '+@orderfield+' desc'';' 
    end 
    else 
    begin 
    set @sqlstr=@sqlstr+'set @sqlstr=''select '+@fieldlist+' from ( select top ''+cast(@nextpagenum as varchar)+'' * from  
 
'+@tablename+'  where '+@strwhere+' order by '+@orderfield+' asc ) as a where '+@keyfield+' not in (  
 
select top ''+cast(@curpagenum as varchar)+'' '+@keyfield+' from '+@tablename+' where '+@strwhere+'  
 
order by '+@orderfield+' asc) order by '+@orderfield+' asc'';' 
    end 
     
    set @sqlstr=@sqlstr+'execute( @sqlstr)' 
    execute(@sqlstr)
    
go


create procedure dbo.HFG_GetResvAll @Confnum nvarchar(50),@uid as
int
as
declare @MyConfnum nvarchar(50)
    
    set @Confnum=replace(@Confnum,'''','''''') 
    set @Confnum=replace(@Confnum,'--','') 
    set @Confnum=replace(@Confnum,';','')
set @MyConfnum =@Confnum

SELECT resvlog.*,hotel.phone,hotel.address1,hotel.address1_e,hotel.checkin,hotel.checkout FROM [resvlog],[hotel] where    confnum=@MyConfnum and (resvlog.propertyid=hotel.pid or resvlog.propertyid=hotel.pid_e)
and verifycode in(select top 1  verifycode from  hfg_scorelog where uid=@uid  and fogid=@Confnum)
go


create procedure dbo.HFG_GetResvAll_Admin @Confnum nvarchar(50),@gid as
int
as
declare @MyConfnum nvarchar(50)
declare @sqlstr nvarchar(1000)
    
    set @Confnum=replace(@Confnum,'''','''''') 
    set @Confnum=replace(@Confnum,'--','') 
    set @Confnum=replace(@Confnum,';','')
set @MyConfnum =@Confnum

set @sqlstr='SELECT resvlog.*,hotel.phone,hotel.address1,hotel.address1_e,hotel.checkin,hotel.checkout FROM [resvlog],[hotel] where    confnum='''+@MyConfnum+''' and (resvlog.propertyid=hotel.pid or resvlog.propertyid=hotel.pid_e)'

if @gid>0
set @sqlstr=@sqlstr+ 'and hotel.groupid='+replace(str(@gid),' ','') +''
exec(@sqlstr)
go


create procedure dbo.HFG_GetUserIsValidateCode @gid as
int ,@username as varchar(50),@checkcode as varchar(50), @type as varchar(1),@hours as int
as 
declare @uid as int
if @hours<0
set @hours=10;
select @uid=uid from hfg_user where
  getdate()<DATEADD(hh,@hours,Checkcodedate)
and usercheckcode = @checkcode and uid in (select uid from  hfg_user_username  where username = @username and  gid=@gid )
 if(@uid>0)
          begin
                 if(@type='e')
                  begin
                      update hfg_user set emailcheck=1,Checkcodedate=getdate(),usercheckcode='' where uid=@uid;
                  end
                  else
                   begin
                      update hfg_user set emailcheck=1,Checkcodedate=getdate() where uid=@uid;  
                   end
                  select 1 as pass   
          end 
  else
          begin
                   select 0 as pass   
          end
go


create procedure dbo.hfg_userscore @uid int 
update hfg_user set scores=(select sum(score)  from hfg_scorelog where uid=@uid and valid=1),scorefreeze=-(select sum(score)  from hfg_scorelog where uid=@uid and valid=1 and scorestatus=1)  where uid=@uid
go


create procedure dbo.HFG_ResvLog_Add @userid int,
 @usertype nvarchar(50),
 @propertyid int,
 @roomtype nvarchar(50),
 @rateclass nvarchar(50),
 @starttime datetime,
 @deptime datetime,
 @updatetime datetime,
 @nights int,
 @room int,
 @guestfirstname nvarchar(50),
 @guestlastname nvarchar(50),
 @guestemail nvarchar(50),
 @guestphone nvarchar(50),
 @guestMP nvarchar(50),
 @guestaddressline1 nvarchar(50),
 @guestaddressline2 nvarchar(50),
 @guestcity nvarchar(50),
 @guestcountry nvarchar(50),
 @gueststate nvarchar(50),
 @guestzip nvarchar(50),
 @cctype nvarchar(50),
 @ccnumber nvarchar(50),
 @ccname nvarchar(50),
 @ccexpyear nvarchar(50),
 @ccexpmonth nvarchar(50),
 @frequentguestid nvarchar(50),
 @iata nvarchar(50),
 @remarks ntext,
 @confnum nvarchar(50),
 @cxlnum nvarchar(50),
 @status nvarchar(50),
 @propertyname nvarchar(500),
 @propertyname_e nvarchar(500),
 @totalmount nvarchar(50),
 @dailyprice nvarchar(500),
 @adults int,
 @children int,
 @plandesc varchar(500),
 @roomname varchar(500),
 @roomdesc varchar(500),
 @canclerule nvarchar(500),
 @guaranteerule nvarchar(500),
 @taxrule nvarchar(500),
 @incomingcall nvarchar(50),
 @fromurl nvarchar(255),
 @deleted int,
 @SubSource nvarchar(50),
 @lastuser nvarchar(50),
 @lastusertype nvarchar(50),
 @verifycode nvarchar(50),
 @getstatus int,
 @flgorder int,
 @departure datetime,
 @payment nvarchar(50),
 @uid int,
 @hid int,
 @gid int,
 @Score as
decimal(18,4)
as
insert into
 resvlog(userid,usertype,propertyid,roomtype,rateclass,starttime,deptime,updatetime,nights,room,guestfirstname,guestlastname,guestemail,guestphone,guestMP,guestaddressline1,guestaddressline2,guestcity,guestcountry,gueststate,guestzip,cctype,ccnumber,ccname,ccexpyear,ccexpmonth,frequentguestid,iata,remarks,confnum,cxlnum,status,propertyname,propertyname_e,totalmount,dailyprice,adults,children,plandesc,roomname,roomdesc,canclerule,guaranteerule,taxRule,incomingcall,fromurl,deleted,SubSource,lastuser,lastuser
type,verifycode,getstatus,flgorder,departure,payment)
 values(@userid,@usertype,@propertyid,@roomtype,@rateclass,@starttime,@deptime,@updatetime,@nights,@room,@guestfirstname,@guestlastname,@guestemail,@guestphone,@guestMP,@guestaddressline1,@guestaddressline2,@guestcity,@guestcountry,@gueststate,@guestzip,@cctype,@ccnumber,@ccname,@ccexpyear,@ccexpmonth,@frequentguestid,@iata,@remarks,@confnum,@cxlnum,@status,@propertyname,@propertyname_e,@totalmount,@dailyprice,@adults,@children,@plandesc,@roomname,@roomdesc,@canclerule,@guaranteerule,@taxrule,@incomingcall
,@fromurl,@deleted,@SubSource,@lastuser,@lastusertype,@verifycode,@getstatus,@flgorder,@departure,@payment);

if(@Score<0)
begin 
insert into  hfg_scorelog
(
Uid,
logdate,
Indate,
Outdate,
bookTotal,
verifycode,
Scorestatus,
Score,
Logsort,
hid,
gid
)
values
(
@uid,
getdate(),
@starttime,
@deptime,
Convert(decimal(18,2),@totalmount),
@verifycode,
1,
@Score,
8,
@hid,
@gid
);
end
else
begin
insert into  hfg_scorelog
(
Uid,
logdate,
Indate,
Outdate,
bookTotal,
verifycode,
Logsort,
hid,
gid
)
values
(
@uid,
getdate(),
@starttime,
@deptime,
Convert(decimal(18,2),@totalmount),
@verifycode,
1,
@hid,
@gid
);


end


exec hfg_userscore @uid;
go


create procedure dbo.HFG_UpdateResvlog_confnum @confnum as
varchar(50),@verifycode as varchar(50),@uid as int
as
begin 
if len(@confnum)>0
begin
 update resvlog set confnum=@confnum,status='New' where verifycode=@verifycode;
 update hfg_scorelog set fogid=@confnum ,scorestatus=0 where verifycode=@verifycode; 
end
else
begin
 update hfg_scorelog set  valid=0  where verifycode=@verifycode; 

end
 exec hfg_userscore @uid; 
end
go


create procedure dbo.HFG_UserInfo @gid as
int ,@uid as int
as
begin
   select a.*,b.username,c.email,d.mobnumb,e.cardnumber from
   (select uid,usrpassword,gid,lvlid,endyear,scores,scorefreeze,usremail,emailformat,emaillanguage,
usrmobile,question,answer,usrfirstname,usrlastname,usrgender,usrbirthday,
usrnationality,idtype,idno,usrcountry,usrprovince,usrcity,smoke,bed,
pillow,regdate,logdate,logip,logcount,usrstatus,emailcheck,usercheckcode,
ademail,admobile,Checkcodedate from hfg_user where gid=@gid and uid=@uid)a left join
hfg_user_username b on a.uid=b.uid left join
hfg_user_email c on a.uid=c.uid  left join 
hfg_user_mobile d on a.uid=d.uid left join
hfg_user_cardnumber e on a.uid=e.uid;
select * from hfg_user_address where uid=@uid;


end
go


create procedure dbo.HFG_UserIsExist @gid as
int,@username as varchar(200),@type as int
as
begin
declare @uid as int
  set @uid=-1;
   if @type=0
   select @uid=uid from hfg_user_username where  username=@username and  gid=@gid;
   else if @type=1
      select  @uid=uid from hfg_user_email where email=@username  and  gid=@gid;
   else if @type=2      
        select  @uid=uid  from hfg_user_mobile where mobnumb=@username   and  gid=@gid;
   else if @type=3
    select  @uid=uid  from  hfg_user_cardnumber where cardnumber=@username   and  gid=@gid;
   select a.*,b.username,c.email,d.mobnumb,e.cardnumber from
   (select uid,usrpassword,gid,lvlid,endyear,scores,scorefreeze,usremail,emailformat,emaillanguage,
usrmobile,question,answer,usrfirstname,usrlastname,usrgender,usrbirthday,
usrnationality,idtype,idno,usrcountry,usrprovince,usrcity,smoke,bed,
pillow,regdate,logdate,logip,logcount,usrstatus,emailcheck,usercheckcode,
ademail,admobile,Checkcodedate from hfg_user where  uid=@uid)a left join
hfg_user_username b on a.uid=b.uid left join
hfg_user_email c on a.uid=c.uid  left join 
hfg_user_mobile d on a.uid=d.uid left join
hfg_user_cardnumber e on a.uid=e.uid
end
go


create procedure dbo.HFG_UserResetPwd @gid as
int,@username as varchar(50),@checkcode as varchar(50),@Pwd as varchar(50)
as
begin
   update hfg_user set usrpassword=@pwd,Checkcodedate=getdate(),usercheckcode='' where
   getdate()<DATEADD(mi,20,Checkcodedate)   and  usercheckcode = @checkcode and uid in(select uid from  hfg_user_username where username = @username and gid=@gid )
end
go


create procedure dbo.HFG_User_Log @uid as
int,@logip as varchar(20)
as
begin
select isnull(logcount,0),isnull(logip,''),isnull(logdate,getdate()) from  hfg_user where uid=@uid;
if @@rowcount=1
update hfg_user set logcount=isnull(logcount,0)+1,logip=@logip,logdate=getdate() where uid=@uid;
end
go


create procedure dbo.HFG_hfg_user_Insert_Web @gid as
int ,@username as varchar(50),@email as varchar(200),@mobnumb  as varchar(20),@pwd as varchar(50),@usercheckcode as varchar(50),@ademail as bit,@admobile as bit
as 
begin
        begin Transaction 
                declare @uid as int;
                insert into  hfg_user(gid,usrpassword,usremail,usrmobile,usercheckcode,ademail,admobile,Checkcodedate)values(@gid,@pwd,@email,@mobnumb,@usercheckcode,@ademail,@admobile,getdate());
                select @uid=SCOPE_IDENTITY();
               
                if @username!=''
                begin
                   insert into hfg_user_username(gid,uid,username)values(@gid,@uid,@username);
                end
                if @email!=''
                begin
                   insert into hfg_user_email(gid,uid,email)values(@gid,@uid,@email);
                end
                if @mobnumb!=''
                begin
                    insert into hfg_user_mobile(gid,uid,mobnumb)values(@gid,@uid,@mobnumb);
                end        
        if @@error=0
        commit Transaction
        else
        rollback Transaction
end
go


create procedure dbo.HFG_hfg_user_IsExist @gid as
int ,@value as varchar(50),@type as varchar(20)
as
begin
        if @Type='username'
        begin
          select count(*) from hfg_user_username where gid=@gid and username=@value;
        end
        if @Type='email'
        begin
          select count(*) from hfg_user_email where gid=@gid and email=@value;
        end
        if @Type='mobile'
        begin
          select count(*) from hfg_user_mobile where gid=@gid and mobnumb=@value;
        end
        if @Type='cardnumber'
        begin
          select count(*) from hfg_user_cardnumber where gid=@gid and cardnumber=@value;
        end
end
go


create procedure dbo.Hotel_CheckRate_H_cache @Property_id int,
 @plancode varchar(50),
 @Chickindate datetime,
 @Chickoutdate datetime as
select [ID],property_id,plancode,convert(nvarchar(10),AvailDate,120) AS AvailDate,singlerate,doublerate,triplerate,quadrate,extraadult,extrachildren,allotment,allotmax,avstat,maxlos,minlos,ratecode,roomcode,tcode,t_from,t_to,roomdesc,ratedesc,gua,cxl,pricenotax,cutoff from H_cache where Property_id=@Property_id and Availdate>=@Chickindate and Availdate<@Chickoutdate and plancode=@plancode order by Availdate
go


create procedure dbo.Hotel_CheckRate_H_cache_bookingengine @Property_id int,
 @plancode varchar(50),
 @Chickindate datetime,
 @Chickoutdate datetime as
select H_cache.*,H_plan.plandesc,H_plan.roomdesc,H_plan.roomname from H_cache,H_plan where H_cache.Property_id=@Property_id and H_cache.Availdate>=@Chickindate and H_cache.Availdate<@Chickoutdate and H_cache.plancode=@plancode and H_cache.plancode=H_plan.plancode
go


create procedure dbo.Hotel_CheckRate_H_cache_mod @Property_id int,
 @plancode varchar(50),
 @Availdate datetime,
 @singlerate decimal,
 @doublerate decimal,
 @triplerate decimal,
 @quadrate decimal,
 @extraadult decimal,
 @extrachildren decimal,
 @Allotment int,
 @AllotMax int,
 @AvStat char(10) as
update   H_cache set   singlerate=@singlerate,doublerate=@doublerate, triplerate=@triplerate, quadrate=@quadrate, extraadult=@extraadult, extrachildren=@extrachildren,Allotment=@Allotment,AllotMax=@AllotMax,AvStat=@AvStat where Property_id=@Property_id and plancode=@plancode and Availdate =@Availdate
go


create procedure dbo.Hubs1_AddResvsms @fixnum nvarchar(10),
 @mobile nvarchar(50),
 @resvdate nvarchar(50),
 @resvtime nvarchar(50),
 @content nvarchar(1000) as
insert into Hubs1_SMSResv(smsid,resvdate,resvtime,resvphone,resvcontent) values(@fixnum,@resvdate,@resvtime,@mobile,@content)
go


create procedure dbo.Hubs1_Addsendsms @mobile nvarchar(50),
 @content nvarchar(160) as
insert into Hubs1_SMSSend(mobile,content) values(@mobile,@content)
go


create procedure dbo.Hubs1_Addsubsms @mobile nvarchar(50),
 @upperid int,
 @content nvarchar(160) as
insert into Hubs1_SMSSend(mobile,content,upperid) values(@mobile,@content,@upperid)
go


create procedure dbo.Hubs1_Sendsms @err int as
BEGIN TRANSACTION

select * from 
(select distinct smsid,content, mobile,upperid  from Hubs1_SMSSend where status=0 and fail<@err) a 
where not exists
(
select * from 
(select distinct content, mobile from Hubs1_SMSSend where status=1 and upperid<>0) b 
where b.content = a.content and a.mobile = b.mobile

)

COMMIT TRANSACTION
go


create procedure dbo.Hubs_GetPage @sql as
nvarchar(4000),@key as nvarchar(100),@field as nvarchar(100),@pagesize as int,@PageIndex as int,@sort as bit
as 


if @sort=1
	begin
	if @key=@field
		begin
		set @sql='select * from ( select '+@sql+')a where '+@key+' in (select '+@key+' from (select top  '+str(@pagesize*@PageIndex)+@sql+'  order by '+@key+' desc)a)and '+@key+' not in (select '+@key+' from (select top '+str(@pagesize*@PageIndex-@pagesize)+'  '+@sql+' order by '+@key+' desc)a) order by '+@field+' desc'
		end
	else 
	        begin
		set @sql='select * from ( select '+@sql+')a where '+@key+' in (select '+@key+' from (select top  '+str(@pagesize*@PageIndex)+@sql+'  order by '+@field+' desc)a)and '+@key+' not in (select '+@key+' from (select top '+str(@pagesize*@PageIndex-@pagesize)+' '+@sql+' order by '+@field+' desc)a) order by '+@field+' desc'
		end
	end
else	
	begin
	if @key=@field
                begin
                 set @sql='select * from ( select '+@sql+')a where '+@key+' in (select '+@key+' from (select top  '+str(@pagesize*@PageIndex)+@sql+'  order by  '+@key+' asc)a)and '+@key+' not in (select '+@key+' from (select top '+str(@pagesize*@PageIndex-@pagesize)+'  '+@sql+' order by  '+@key+' asc)a) order by '+@field+' asc'
                end
		
	else
	        begin
		set @sql='select * from ( select '+@sql+')a where '+@key+' in (select '+@key+' from (select top  '+str(@pagesize*@PageIndex)+@sql+'  order by '+@field+' asc)a)and '+@key+' not in (select '+@key+' from (select top '+str(@pagesize*@PageIndex-@pagesize)+'  '+@sql+' order by '+@field+' asc)a) order by '+@field+' asc'
	        end
        end
exec( @sql)
go


create procedure dbo.Hubs_HotHotelResult_Insert as
begin
        declare @From as datetime,@End as datetime,@cur as datetime, @count as int;
        set @cur=Convert(varchar(10),getdate(),120);
        set @From=dateadd(dd,-(7+DatePart(w,@cur)),@cur)
        set @End=dateadd(dd,-(-1+DatePart(w,@cur)),@cur) 
        select @count=count(*) from  Hubs_HotHotelResult  where DateFrom=@From and DateEnd=@End
        
        if(@count<1)
        begin
        select propertyid, sum(nights*room) as nights into #tempHotel  from  resvlog where status!='cxl' and  updatetime>=@From  and updatetime<@End group by propertyid
        insert into Hubs_HotHotelResult(CityID,Hotel_ID,Pid,nights,DateFrom,DateEnd)
        select b.cityid,b.Hotel_ID,b.pid,a.nights,@From,@End   from #tempHotel a inner join Hotel b on b.GroupID<>9 and  not(b.CityID is null) and a.propertyid=b.pid order by a.nights
        drop table #tempHotel
        end
end
go


create procedure dbo.Hubs_HotHotelResult_Insert_DFB as
begin
        declare @From as datetime,@End as datetime,@cur as datetime, @count as int;
        set @cur=Convert(varchar(10),getdate(),120);
        set @From=dateadd(dd,-(7+DatePart(w,@cur)),@cur)
        set @End=dateadd(dd,-(-1+DatePart(w,@cur)),@cur) 
        select @count=count(*) from  Hubs_HotHotelResult  where DateFrom=@From and DateEnd=@End
        
        if(@count<1)
        begin
        select propertyid, sum(nights*room) as nights into #tempHotel  from  resvlog where status!='cxl' and  updatetime>=@From  and updatetime<@End group by propertyid
        insert into Hubs_HotHotelResult(CityID,Hotel_ID,Pid,nights,DateFrom,DateEnd)
        select b.cityid,b.Hotel_ID,b.pid,a.nights,@From,@End   from #tempHotel a inner join Hotel b on b.GroupID<>9 and  not(b.CityID is null) and a.propertyid=b.pid order by a.nights
        drop table #tempHotel
        end
end
go


create procedure dbo.Hubs_HotHotelResult_TopCity as
begin
        EXEC Hubs_HotHotelResult_Insert;
        declare @From as datetime,@End as datetime,@cur as datetime
        set @cur=Convert(varchar(10),getdate(),120);
        set @From=dateadd(dd,-(7+DatePart(w,@cur)),@cur)
        set @End=dateadd(dd,-(-1+DatePart(w,@cur)),@cur) 
        select a.CityID,a.[Name] from H_City a inner join 
        (select top 3 CityID,sum(nights) as night from Hubs_HotHotelResult  where DateFrom=@From and DateEnd=@End group by CityID order by night desc)b 
        on a.CityID=b.CityID order by b.night desc 
end

go


create procedure dbo.Hubs_HotHotelResult_TopHotel @cityID as
int
as 
begin
        EXEC Hubs_HotHotelResult_Insert;
       
        declare @From as datetime,@End as datetime,@cur as datetime
        set @cur=Convert(varchar(10),getdate(),120);
        set @From=dateadd(dd,-(7+DatePart(w,@cur)),@cur)
        set @End=dateadd(dd,-(-1+DatePart(w,@cur)),@cur) 
        if(@CityID=0)
        begin         
        select top 30 a.Hotel_ID,a.Pid,a.Title,a.Stars,a.Diamond,a.Address1,a.CityID,c.[Name] from Hotel a inner join Hubs_HotHotelResult b
        on a.Hotel_ID=b.Hotel_ID inner join H_City c on b.CityID=c.CityID  and  b.DateFrom=@From and b.DateEnd=@End  order by b.nights  desc      
        end
        else
        begin
            select top 3 a.Hotel_ID,a.Pid,a.Title,a.Stars,a.Diamond  from Hotel a inner join Hubs_HotHotelResult b
        on a.Hotel_ID=b.Hotel_ID and b.cityID=@CityID  and  b.DateFrom=@From and b.DateEnd=@End  order by b.nights  desc      

        end
end
go


create procedure dbo.Hubs_HotHotelResult_TopHotel_DFB @cityID as
int,
@rows as int
as 
begin
        EXEC Hubs_HotHotelResult_Insert_DFB;
        declare @From as datetime,@End as datetime,@cur as datetime,@sql nvarchar(2000)
        set @cur=Convert(varchar(10),getdate(),120);
        set @From=dateadd(dd,-(7+DatePart(w,@cur)),@cur)
        set @End=dateadd(dd,-(-7+DatePart(w,@cur)),@cur) 
        if(@CityID=0)
        begin       
        set @sql='select top '+cast(@rows as varchar(8))+ ' a.Hotel_ID,a.Pid,a.Title,a.Stars,a.Diamond,a.Address1,a.CityID,c.[Name] from Hotel a inner join Hubs_HotHotelResult b
        on a.Hotel_ID=b.Hotel_ID inner join H_City c on b.CityID=c.CityID  and b.DateFrom='''+convert(varchar(10),@From,120)+''' and b.DateEnd='''+convert(varchar(10),@End,120)+''' order by b.nights  desc '     
        end
        else
        begin
        set @sql='select top '+cast(@rows as varchar(8))+'  a.Hotel_ID,a.Pid,a.Title,a.Stars,a.Diamond  from Hotel a inner join Hubs_HotHotelResult b
        on a.Hotel_ID=b.Hotel_ID and b.cityID='+cast(@CityID as varchar(8))+'  and  b.DateFrom='''+convert(varchar(10),@From,120)+''' and b.DateEnd='''+convert(varchar(10),@End,120)+'''  order by b.nights  desc'      
        end
	exec(@sql)
end
go


create procedure dbo.sms_send_Add @orig_mobile nvarchar(50),
 @content nvarchar(160) as
insert into sms_send(orig_mobile,content) values(@orig_mobile,@content)
go


create procedure dbo.Insert_FIT_CMB_MobileValidate @MobileNo as
varchar(11),@validateCode as varchar(20),@IPAddress as varchar(24),@SessionID as varchar(200),@MName as varchar(200)
as 
  declare @temp as varchar(100);
  set @temp='您的酒店预订手机确认码是:'+@validateCode+';招行卡中心指定服务商';

	  Insert into FIT_MobileValidate(MobileNo,validateCode,IPAddress,SessionID,MName)values(@MobileNo,@validateCode,@IPAddress,@SessionID,@MName);
	  exec sms_send_Add  @MobileNo,@temp
go


create procedure dbo.Insert_FIT_MobileValidate @MobileNo as
varchar(11),@validateCode as varchar(20),@IPAddress as varchar(24),@SessionID as varchar(200),@MName as varchar(200)
as 
  declare @temp as varchar(100);
  set @temp='您的酒店预订手机确认码是:'+@validateCode;

	  Insert into FIT_MobileValidate(MobileNo,validateCode,IPAddress,SessionID,MName)values(@MobileNo,@validateCode,@IPAddress,@SessionID,@MName);
	  exec sms_send_Add  @MobileNo,@temp
go


create procedure dbo.Insert_FIT_SHZAir_MobileValidate @MobileNo as
varchar(11),@validateCode as varchar(20),@IPAddress as varchar(24),@SessionID as varchar(200),@MName as varchar(200)
as 
  declare @temp as varchar(100);
  set @temp='您的酒店预订手机确认码是:'+@validateCode+';深航酒店预订服务商';

	  Insert into FIT_MobileValidate(MobileNo,validateCode,IPAddress,SessionID,MName)values(@MobileNo,@validateCode,@IPAddress,@SessionID,@MName);
	  exec sms_send_Add  @MobileNo,@temp
go


create function dbo.Pay_GetChinaPay_BillNO (@date as datetime,@MID as varchar(9))
returns  varchar(16)
as
begin
declare @NO as varchar(16);
set @MID=left(Convert(varchar(10),@date,12),4)+@MID;
select  @NO=Max(billNO) from pay  where payman='chinapay' and left(billNO,9)=@MID
if @NO is null
 set  @NO=0;
else
 set @NO=replace(@NO,@MID,'');
set @NO=@MID+right('000000'+convert(varchar,(Convert(int,@NO)+1)),7)
return @NO
end
go


create procedure dbo.ResvLog_Add @userid int,
 @usertype nvarchar(50),
 @propertyid int,
 @roomtype nvarchar(50),
 @rateclass nvarchar(50),
 @starttime datetime,
 @deptime datetime,
 @updatetime datetime,
 @nights int,
 @room int,
 @guestfirstname nvarchar(50),
 @guestlastname nvarchar(50),
 @guestemail nvarchar(50),
 @guestphone nvarchar(50),
 @guestMP nvarchar(50),
 @guestaddressline1 nvarchar(50),
 @guestaddressline2 nvarchar(50),
 @guestcity nvarchar(50),
 @guestcountry nvarchar(50),
 @gueststate nvarchar(50),
 @guestzip nvarchar(50),
 @cctype nvarchar(50),
 @ccnumber nvarchar(50),
 @ccname nvarchar(50),
 @ccexpyear nvarchar(50),
 @ccexpmonth nvarchar(50),
 @frequentguestid nvarchar(50),
 @iata nvarchar(50),
 @remarks ntext,
 @confnum nvarchar(50),
 @cxlnum nvarchar(50),
 @status nvarchar(50),
 @propertyname nvarchar(500),
 @propertyname_e nvarchar(500),
 @totalmount nvarchar(50),
 @dailyprice varchar(2000),
 @adults int,
 @children int,
 @plandesc varchar(500),
 @roomname varchar(500),
 @roomdesc varchar(500),
 @canclerule nvarchar(500),
 @guaranteerule nvarchar(500),
 @taxrule nvarchar(500),
 @incomingcall nvarchar(50),
 @fromurl nvarchar(255),
 @deleted int,
 @SubSource nvarchar(50),
 @lastuser nvarchar(50),
 @lastusertype nvarchar(50),
 @verifycode nvarchar(50),
 @getstatus int,
 @flgorder int,
 @departure datetime as
insert into
 resvlog(userid,usertype,propertyid,roomtype,rateclass,starttime,deptime,updatetime,nights,room,guestfirstname,guestlastname,guestemail,guestphone,guestMP,guestaddressline1,guestaddressline2,guestcity,guestcountry,gueststate,guestzip,cctype,ccnumber,ccname,ccexpyear,ccexpmonth,frequentguestid,iata,remarks,confnum,cxlnum,status,propertyname,propertyname_e,totalmount,dailyprice,adults,children,plandesc,roomname,roomdesc,canclerule,guaranteerule,taxRule,incomingcall,fromurl,deleted,SubSource,lastuser,lastuser
type,verifycode,getstatus,flgorder,departure)
 values(@userid,@usertype,@propertyid,@roomtype,@rateclass,@starttime,@deptime,@updatetime,@nights,@room,@guestfirstname,@guestlastname,@guestemail,@guestphone,@guestMP,@guestaddressline1,@guestaddressline2,@guestcity,@guestcountry,@gueststate,@guestzip,@cctype,@ccnumber,@ccname,@ccexpyear,@ccexpmonth,@frequentguestid,@iata,@remarks,@confnum,@cxlnum,@status,@propertyname,@propertyname_e,@totalmount,@dailyprice,@adults,@children,@plandesc,@roomname,@roomdesc,@canclerule,@guaranteerule,@taxrule,@incomingcall
,@fromurl,@deleted,@SubSource,@lastuser,@lastusertype,@verifycode,@getstatus,@flgorder,@departure)
go


create procedure dbo.ResvLog_Add1 @userid int,
 @usertype nvarchar(50),
 @propertyid int,
 @roomtype nvarchar(50),
 @rateclass nvarchar(50),
 @starttime datetime,
 @deptime datetime,
 @updatetime datetime,
 @nights int,
 @room int,
 @guestfirstname nvarchar(50),
 @guestlastname nvarchar(50),
 @guestemail nvarchar(50),
 @guestphone nvarchar(50),
 @guestaddressline1 nvarchar(50),
 @guestaddressline2 nvarchar(50),
 @guestcity nvarchar(50),
 @guestcountry nvarchar(50),
 @gueststate nvarchar(50),
 @guestzip nvarchar(50),
 @cctype nvarchar(50),
 @ccnumber nvarchar(50),
 @ccname nvarchar(50),
 @ccexpyear nvarchar(50),
 @ccexpmonth nvarchar(50),
 @frequentguestid nvarchar(50),
 @iata nvarchar(50),
 @remarks ntext,
 @confnum nvarchar(50),
 @cxlnum nvarchar(50),
 @status nvarchar(50),
 @propertyname nvarchar(500),
 @propertyname_e nvarchar(500),
 @totalmount nvarchar(50),
 @totalrevenue decimal(18,2),
 @dailyprice varchar(2000),
 @adults int,
 @children int,
 @plandesc varchar(500),
 @roomname varchar(500),
 @roomdesc varchar(500),
 @canclerule nvarchar(500),
 @guaranteerule nvarchar(500),
 @incomingcall nvarchar(50),
 @fromurl nvarchar(255),
 @deleted int,
 @SubSource nvarchar(50),
 @lastuser nvarchar(50),
 @lastusertype nvarchar(50),
 @verifycode nvarchar(50),
 @getstatus int,
 @flgorder int,
 @departure datetime,
 @pmsno nvarchar(50),
 @roomno nvarchar(50) as
insert into
 resvlog(userid,usertype,propertyid,roomtype,rateclass,starttime,deptime,updatetime,nights,room,guestfirstname,guestlastname,guestemail,guestphone,guestaddressline1,guestaddressline2,guestcity,guestcountry,gueststate,guestzip,cctype,ccnumber,ccname,ccexpyear,ccexpmonth,frequentguestid,iata,remarks,confnum,cxlnum,status,propertyname,propertyname_e,totalmount,totalrevenue,dailyprice,adults,children,plandesc,roomname,roomdesc,canclerule,guaranteerule,incomingcall,fromurl,deleted,SubSource,lastuser,lastusertyp
e,verifycode,getstatus,flgorder,departure,pmsno,roomno)
 values(@userid,@usertype,@propertyid,@roomtype,@rateclass,@starttime,@deptime,@updatetime,@nights,@room,@guestfirstname,@guestlastname,@guestemail,@guestphone,@guestaddressline1,@guestaddressline2,@guestcity,@guestcountry,@gueststate,@guestzip,@cctype,@ccnumber,@ccname,@ccexpyear,@ccexpmonth,@frequentguestid,@iata,@remarks,@confnum,@cxlnum,@status,@propertyname,@propertyname_e,@totalmount,@totalrevenue,@dailyprice,@adults,@children,@plandesc,@roomname,@roomdesc,@canclerule,@guaranteerule,@incomingcall,@fr
omurl,@deleted,@SubSource,@lastuser,@lastusertype,@verifycode,@getstatus,@flgorder,@departure,@pmsno,@roomno)
go


create procedure dbo.ResvLog_Add_Payment @userid int,
 @usertype nvarchar(50),
 @propertyid int,
 @roomtype nvarchar(50),
 @rateclass nvarchar(50),
 @starttime datetime,
 @deptime datetime,
 @updatetime datetime,
 @nights int,
 @room int,
 @guestfirstname nvarchar(50),
 @guestlastname nvarchar(50),
 @guestemail nvarchar(50),
 @guestphone nvarchar(50),
 @guestMP nvarchar(50),
 @guestaddressline1 nvarchar(50),
 @guestaddressline2 nvarchar(50),
 @guestcity nvarchar(50),
 @guestcountry nvarchar(50),
 @gueststate nvarchar(50),
 @guestzip nvarchar(50),
 @cctype nvarchar(50),
 @ccnumber nvarchar(50),
 @ccname nvarchar(50),
 @ccexpyear nvarchar(50),
 @ccexpmonth nvarchar(50),
 @frequentguestid nvarchar(50),
 @iata nvarchar(50),
 @remarks ntext,
 @confnum nvarchar(50),
 @cxlnum nvarchar(50),
 @status nvarchar(50),
 @propertyname nvarchar(500),
 @propertyname_e nvarchar(500),
 @totalmount nvarchar(50),
 @dailyprice varchar(2000),
 @adults int,
 @children int,
 @plandesc varchar(500),
 @roomname varchar(500),
 @roomdesc varchar(500),
 @canclerule nvarchar(500),
 @guaranteerule nvarchar(500),
 @taxrule nvarchar(500),
 @incomingcall nvarchar(50),
 @fromurl nvarchar(255),
 @deleted int,
 @SubSource nvarchar(50),
 @lastuser nvarchar(50),
 @lastusertype nvarchar(50),
 @verifycode nvarchar(50),
 @getstatus int,
 @flgorder int,
 @departure datetime,
 @payment nvarchar(50),
 @CurrencyCode varchar(5) as
insert into
 resvlog(userid,usertype,propertyid,roomtype,rateclass,starttime,deptime,updatetime,nights,room,guestfirstname,guestlastname,guestemail,guestphone,guestMP,guestaddressline1,guestaddressline2,guestcity,guestcountry,gueststate,guestzip,cctype,ccnumber,ccname,ccexpyear,ccexpmonth,frequentguestid,iata,remarks,confnum,cxlnum,status,propertyname,propertyname_e,totalmount,dailyprice,adults,children,plandesc,roomname,roomdesc,canclerule,guaranteerule,taxRule,incomingcall,fromurl,deleted,SubSource,lastuser,lastuser
type,verifycode,getstatus,flgorder,departure,payment,CurrencyCode)
 values(@userid,@usertype,@propertyid,@roomtype,@rateclass,@starttime,@deptime,@updatetime,@nights,@room,@guestfirstname,@guestlastname,@guestemail,@guestphone,@guestMP,@guestaddressline1,@guestaddressline2,@guestcity,@guestcountry,@gueststate,@guestzip,@cctype,@ccnumber,@ccname,@ccexpyear,@ccexpmonth,@frequentguestid,@iata,@remarks,@confnum,@cxlnum,@status,@propertyname,@propertyname_e,@totalmount,@dailyprice,@adults,@children,@plandesc,@roomname,@roomdesc,@canclerule,@guaranteerule,@taxrule,@incomingcall
,@fromurl,@deleted,@SubSource,@lastuser,@lastusertype,@verifycode,@getstatus,@flgorder,@departure,@payment,@CurrencyCode)
go


create procedure dbo.ResvLog_Add_stat @userid int,
 @usertype nvarchar(50),
 @propertyid int,
 @roomtype nvarchar(50),
 @rateclass nvarchar(50),
 @starttime datetime,
 @deptime datetime,
 @updatetime datetime,
 @nights int,
 @room int,
 @guestfirstname nvarchar(50),
 @guestlastname nvarchar(50),
 @guestemail nvarchar(50),
 @guestphone nvarchar(50),
 @guestaddressline1 nvarchar(50),
 @guestaddressline2 nvarchar(50),
 @guestcity nvarchar(50),
 @guestcountry nvarchar(50),
 @gueststate nvarchar(50),
 @guestzip nvarchar(50),
 @cctype nvarchar(50),
 @ccnumber nvarchar(50),
 @ccname nvarchar(50),
 @ccexpyear nvarchar(50),
 @ccexpmonth nvarchar(50),
 @frequentguestid nvarchar(50),
 @iata nvarchar(50),
 @remarks ntext,
 @confnum nvarchar(50),
 @cxlnum nvarchar(50),
 @status nvarchar(50),
 @propertyname nvarchar(500),
 @propertyname_e nvarchar(500),
 @totalmount nvarchar(50),
 @totalrevenue decimal(18,2),
 @dailyprice varchar(2000),
 @adults int,
 @children int,
 @plandesc varchar(500),
 @roomname varchar(500),
 @roomdesc varchar(500),
 @canclerule nvarchar(500),
 @guaranteerule nvarchar(500),
 @incomingcall nvarchar(50),
 @fromurl nvarchar(255),
 @deleted int,
 @SubSource nvarchar(50),
 @lastuser nvarchar(50),
 @lastusertype nvarchar(50),
 @verifycode nvarchar(50),
 @getstatus int,
 @flgorder int,
 @departure datetime,
 @pmsno nvarchar(50),
 @roomno nvarchar(50) as
insert into
 resvlog(userid,usertype,propertyid,roomtype,rateclass,starttime,deptime,updatetime,nights,room,guestfirstname,guestlastname,guestemail,guestphone,guestaddressline1,guestaddressline2,guestcity,guestcountry,gueststate,guestzip,cctype,ccnumber,ccname,ccexpyear,ccexpmonth,frequentguestid,iata,remarks,confnum,cxlnum,status,propertyname,propertyname_e,totalmount,totalrevenue,dailyprice,adults,children,plandesc,roomname,roomdesc,canclerule,guaranteerule,incomingcall,fromurl,deleted,SubSource,lastuser,lastusertyp
e,verifycode,getstatus,flgorder,departure,pmsno,roomno)
 values(@userid,@usertype,@propertyid,@roomtype,@rateclass,@starttime,@deptime,@updatetime,@nights,@room,@guestfirstname,@guestlastname,@guestemail,@guestphone,@guestaddressline1,@guestaddressline2,@guestcity,@guestcountry,@gueststate,@guestzip,@cctype,@ccnumber,@ccname,@ccexpyear,@ccexpmonth,@frequentguestid,@iata,@remarks,@confnum,@cxlnum,@status,@propertyname,@propertyname_e,@totalmount,@totalrevenue,@dailyprice,@adults,@children,@plandesc,@roomname,@roomdesc,@canclerule,@guaranteerule,@incomingcall,@fr
omurl,@deleted,@SubSource,@lastuser,@lastusertype,@verifycode,@getstatus,@flgorder,@departure,@pmsno,@roomno)
go


create procedure dbo.ResvLog_Mod @userid int,
 @usertype nvarchar(50),
 @propertyid int,
 @roomtype nvarchar(50),
 @rateclass nvarchar(50),
 @starttime datetime,
 @deptime datetime,
 @updatetime datetime,
 @nights int,
 @room int,
 @guestfirstname nvarchar(50),
 @guestlastname nvarchar(50),
 @guestemail nvarchar(50),
 @guestphone nvarchar(50),
 @guestMP nvarchar(50),
 @guestaddressline1 nvarchar(50),
 @guestaddressline2 nvarchar(50),
 @guestcity nvarchar(50),
 @guestcountry nvarchar(50),
 @gueststate nvarchar(50),
 @guestzip nvarchar(50),
 @cctype nvarchar(50),
 @ccnumber nvarchar(50),
 @ccname nvarchar(50),
 @ccexpyear nvarchar(50),
 @ccexpmonth nvarchar(50),
 @frequentguestid nvarchar(50),
 @iata nvarchar(50),
 @remarks ntext,
 @confnum nvarchar(50),
 @cxlnum nvarchar(50),
 @status nvarchar(50),
 @propertyname nvarchar(500),
 @propertyname_e nvarchar(500),
 @totalmount nvarchar(50),
 @dailyprice varchar(2000),
 @adults int,
 @children int,
 @plandesc varchar(500),
 @roomname varchar(500),
 @roomdesc varchar(500),
 @canclerule nvarchar(500),
 @guaranteerule nvarchar(500),
 @taxrule nvarchar(500),
 @incomingcall nvarchar(50),
 @fromurl nvarchar(255),
 @deleted int,
 @SubSource nvarchar(50),
 @lastuser nvarchar(50),
 @lastusertype nvarchar(50),
 @verifycode nvarchar(50),
 @CurrencyCode varchar(5) as
update resvlog set 
 userid=@userid,usertype=@usertype,propertyid=@propertyid,roomtype=@roomtype,rateclass=@rateclass,starttime=@starttime,deptime=@deptime,updatetime=@updatetime,nights=@nights,room=@room,guestfirstname=@guestfirstname,guestlastname=@guestlastname,guestemail=@guestemail,guestphone=@guestphone,guestMP=@guestMP,guestaddressline1=@guestaddressline1,guestaddressline2=@guestaddressline2,guestcity=@guestcity,guestcountry=@guestcountry,gueststate=@gueststate,guestzip=@guestzip,cctype=@cctype,ccnumber=@ccnumber,ccnam
e=@ccname,ccexpyear=@ccexpyear,ccexpmonth=@ccexpmonth,frequentguestid=@frequentguestid,iata=@iata,confnum=@confnum,cxlnum=@cxlnum,status=@status,propertyname=@propertyname,propertyname_e=@propertyname_e,totalmount=@totalmount,dailyprice=@dailyprice,adults=@adults,children=@children,plandesc=@plandesc,roomname=@roomname,roomdesc=@roomdesc,canclerule=@canclerule,guaranteerule=@guaranteerule,taxRule=@taxrule,incomingcall=@incomingcall,fromurl=@fromurl,deleted=@deleted,SubSource=@SubSource,lastuser=@lastuser,l
astusertype=@lastusertype,CurrencyCode=@CurrencyCode where propertyid=@propertyid and verifycode=@verifycode;
update resvlog set  remarks=@remarks where propertyid=@propertyid and verifycode=@verifycode;
go


create procedure dbo.ResvLog_Sel @verifycode nvarchar(50) as
select * from  resvlog where  verifycode=@verifycode
go


create procedure dbo.Resvlog_Update_CheckResv @getstatus nvarchar(50),
 @departure nvarchar(10),
 @pmsno nvarchar(100),
 @roomno nvarchar(100),
 @confnum nvarchar(100) as
set @departure=replace(@departure,'''','''''') 
    set @departure=replace(@departure,'--','') 
    set @departure=replace(@departure,';','')

    set @pmsno=replace(@pmsno,'''','''''') 
    set @pmsno=replace(@pmsno,'--','') 
    set @pmsno=replace(@pmsno,';','')

    set @roomno=replace(@roomno,'''','''''') 
    set @roomno=replace(@roomno,'--','') 
    set @roomno=replace(@roomno,';','')
update resvlog set
getstatus=@getstatus,departure=@departure,pmsno=@pmsno,roomno=@roomno
where confnum=@confnum
go


create procedure dbo.Resvlog_Update_PmsRoom @pmsno nvarchar(100),
 @roomno nvarchar(100),
 @confnum nvarchar(50) as
update resvlog 
set
pmsno=@pmsno,roomno=@roomno
where confnum=@confnum
go


create procedure dbo.SearchHotel @Title nvarchar(50),
 @City nvarchar(50),
 @CheckIn datetime,
 @CheckOut datetime,
 @PriceRange nvarchar(50),
 @AirPortDistance int,
 @Stars int,
 @AirPortCode nvarchar(50),
 @ConfirmationType nvarchar(50),
 @Plan nvarchar(500), 
 @GroupID nvarchar(500), 
 @PageSize int=10, 
 @CurPage int=1, 
 @doCount int 
declare @MyTitle nvarchar(50)
    
    set @Title=replace(@Title,'''','''''') 
    set @Title=replace(@Title,'--','') 
    set @Title=replace(@Title,';','') 
set @MyTitle = '%'+@Title+'%'

declare @MyCity nvarchar(50)
    
    set @City=replace(@City,'''','''''') 
    set @City=replace(@City,'--','') 
    set @City=replace(@City,';','') 
set @MyCity = '%'+@City+'%'


declare @s varchar(6000) 
declare @stemp varchar(6000) 
if (@doCount != 0)  
begin 
set @s ='select count(*) as Total from dbo.Hotel '
end
else
begin
set @s ='select  top ' + cast(@PageSize as nvarchar(20)) + ' * from dbo.Hotel '
end

if (@GroupID != '')  
begin 
set @s =@s+' where '+@GroupID
end
else
begin
set @s =@s+' where 1=1 '
end

set @stemp =''


if (@Title!='')
set @stemp =@stemp+'and (Title like '''+@MyTitle+''' or Title_e like '''+@MyTitle+''' )'

if (@Stars!=10)
set @stemp =@stemp+' and Stars ='+ cast(@Stars as varchar)


	

if (@City!='')
	begin
	set @stemp =@stemp+ ' and (classid in(select city.classid from city where parentid in(select city.classid from city where ClassName like '''+@MyCity+''' or ClassName_e like '''+@MyCity+''')) or classid in (select city.classid from city where ClassName like '''+@MyCity+''' or ClassName_e like '''+@MyCity+'''))'
	end
	




set @stemp =@stemp+ ' and (pid in(select distinct property_id from h_cache where '
if (@Plan!='')
	begin
	set @stemp =@stemp+@Plan+ '  and  '
	end
if (@PriceRange!='')
begin
	declare @MyPriceRange nvarchar(100)

	if (@PriceRange='<=250')
	set @MyPriceRange ='priceNoTax>0 and priceNoTax<= 250'
	if (@PriceRange='250-400')
	set @MyPriceRange ='priceNoTax>250 and priceNoTax<=400'
	if (@PriceRange='400-600')
	set @MyPriceRange ='priceNoTax>400 and priceNoTax<=600'
	if (@PriceRange='600-800')
	set @MyPriceRange ='priceNoTax>600 and priceNoTax<=800'
	if (@PriceRange='>800')
	set @MyPriceRange ='priceNoTax> 800'

	set @stemp =@stemp +@MyPriceRange+' '
	
end
else
begin
set @stemp =@stemp+ '  priceNoTax>0 '
end

set @stemp =@stemp+ '  and avstat!=''N''  and (datediff(hh,getdate(),Availdate)+24>=cutoff)  and  Availdate>= '''+convert(varchar(10),@CheckIn,120)+''' AND Availdate<'''+convert(varchar(10),@CheckOut,120)+''') )'



if (@doCount =0)
	begin
	if (@CurPage!=1)
		
		begin		
		declare @PageIndex int
		set @PageIndex=(@CurPage-1)*@PageSize
		set @s =@s+@stemp+' and Hotel_ID not in(select top ' + cast(@PageIndex as nvarchar(20)) + ' Hotel_ID from hotel where 1=1 '+@stemp+ ' order by pagerank desc,hotel_id) order by pagerank desc,hotel_id'
		end

	else
	begin
	set @s =@s+@stemp+'order by pagerank desc,hotel_id '
	end
	end
else
set @s =@s+@stemp
print @s
exec ( @s )
go


create procedure dbo.SearchHotel2 <@arg> <type> as
declare <@var> <type>
begin

end
go


create procedure dbo.SearchHotel3 <@arg> <type> as
declare <@var> <type>
begin

end
go


create procedure SearchHotel4 @Title nvarchar(50),
 @City nvarchar(50),
 @CheckIn datetime,
 @CheckOut datetime,
 @PriceRange nvarchar(50),
 @AirPortDistance int,
 @Stars int,
 @AirPortCode nvarchar(50),
 @ConfirmationType nvarchar(50),
 @Plan nvarchar(500), 
 @GroupID nvarchar(500), 
 @PageSize int=10, 
 @CurPage int=1, 
 @lastcount int, 
 @doCount int 
declare @MyTitle nvarchar(50)
    
    set @Title=replace(@Title,'''','''''') 
    set @Title=replace(@Title,'--','') 
    set @Title=replace(@Title,';','') 
set @MyTitle = '%'+@Title+'%'

declare @MyCity nvarchar(50)
    
    set @City=replace(@City,'''','''''') 
    set @City=replace(@City,'--','') 
    set @City=replace(@City,';','') 
set @MyCity = '%'+@City+'%'


declare @s varchar(6000) 
declare @stemp varchar(6000) 
if (@doCount != 0)  
begin 
set @s ='select count(*) as Total from dbo.Hotel '
end
else
begin
declare @PageIndex int
set @PageIndex=@CurPage*@PageSize
if(@lastcount < @PageSize)
begin
set @s ='select  * from (select top ' + cast(@lastcount as nvarchar(20)) + ' * from (select top ' +cast(@PageIndex as nvarchar(20)) + ' * from dbo.Hotel '
end
else
begin
set @s ='select  * from (select top ' + cast(@PageSize as nvarchar(20)) + ' * from (select top ' +cast(@PageIndex as nvarchar(20)) + ' * from dbo.Hotel '
end
end

if (@GroupID != '')  
begin 
set @s =@s+' where '+@GroupID
end
else
begin
set @s =@s+' where 1=1 '
end

set @stemp =''


if (@Title!='')
set @stemp =@stemp+'and (Title like '''+@MyTitle+''' or Title_e like '''+@MyTitle+''' )'

if (@Stars!=10)
set @stemp =@stemp+' and Stars ='+ cast(@Stars as varchar)


	

if (@City!='')
	begin
	set @stemp =@stemp+ ' and (classid in(select city.classid from city where parentid in(select city.classid from city where ClassName like '''+@MyCity+''' or ClassName_e like '''+@MyCity+''')) or classid in (select city.classid from city where ClassName like '''+@MyCity+''' or ClassName_e like '''+@MyCity+'''))'
	end
	




set @stemp =@stemp+ ' and (pid in(select distinct property_id from h_cache where '
if (@Plan!='')
	begin
	set @stemp =@stemp+@Plan+ '  and  '
	end
if (@PriceRange!='')
begin
	declare @MyPriceRange nvarchar(100)

	if (@PriceRange='<=250')
	set @MyPriceRange ='priceNoTax>0 and priceNoTax<= 250'
	if (@PriceRange='250-400')
	set @MyPriceRange ='priceNoTax>250 and priceNoTax<=400'
	if (@PriceRange='400-600')
	set @MyPriceRange ='priceNoTax>400 and priceNoTax<=600'
	if (@PriceRange='600-800')
	set @MyPriceRange ='priceNoTax>600 and priceNoTax<=800'
	if (@PriceRange='>800')
	set @MyPriceRange ='priceNoTax> 800'

	set @stemp =@stemp +@MyPriceRange+' '
	
end
else
begin
set @stemp =@stemp+ '  priceNoTax>0 '
end

set @stemp =@stemp+ '  and avstat!=''N''  and (datediff(hh,getdate(),Availdate)+24>=cutoff)  and  Availdate>= '''+convert(varchar(10),@CheckIn,120)+''' AND Availdate<'''+convert(varchar(10),@CheckOut,120)+''') )'



if (@doCount =0)
begin
set @s =@s+@stemp+ ' order by pagerank desc,hotel_id ) as aa order by pagerank ,hotel_id desc) as aa order by pagerank desc,hotel_id'
end
else
set @s =@s+@stemp

exec ( @s )
go


create procedure dbo.SearchHotelDFB @Title nvarchar(50),
 @City int,
 @District int,
 @Commercial int,
 @CheckIn datetime,
 @CheckOut datetime,
 @PriceRange nvarchar(50),
 @Stars int,
 @Plan nvarchar(500), 
 @GroupID nvarchar(2000), 
 @Child int,
 @Adult int,
 @PageSize int=10, 
 @CurPage int=1, 
 @doCount int 
declare @MyTitle nvarchar(50)
    
    set @Title=replace(@Title,'''','''''') 
    set @Title=replace(@Title,'--','') 
    set @Title=replace(@Title,';','') 
set @MyTitle = '%'+@Title+'%'


    
   
   
    



declare @s varchar(6000) 
declare @stemp varchar(6000) 
if (@doCount != 0)  
begin 
set @s ='select count(*) as Total from dbo.Hotel '
end
else
begin
declare @PageIndex int
set @PageIndex=@CurPage*@PageSize
set @s ='select  top ' + cast(@PageSize as nvarchar(20)) + ' * from (select top ' + cast(@PageSize as nvarchar(20)) + ' * from (select top ' +cast(@PageIndex as nvarchar(20)) + ' * from dbo.Hotel '
end

if (@GroupID != '')  
begin 
set @s =@s+' where  passed=1 and  '+@GroupID
end
else
begin
set @s =@s+' where passed=1 '
end

set @stemp =''


if (@Title!='')
set @stemp =@stemp+'and (Title like '''+@MyTitle+''' or Title_e like '''+@MyTitle+''' or keywords like ''%'+@MyTitle+'%'' )'

if (@Stars!=10)
	begin
		if(@Stars=0)
			set @stemp =@stemp+' and (Stars =0 and Diamond=0)'
		else
			set @stemp =@stemp+' and ((Stars ='+ cast(@Stars as varchar)+' and Diamond=0)  or (Diamond='+ cast(@Stars as varchar)+' and Stars=0))'
	end

	


	
	
	

if (@City!=-1)
set @stemp=@stemp+' and cityid='+ cast(@City as varchar)

if (@District!=-1)
set @stemp=@stemp+' and districtid='+ cast(@District as varchar)

if (@Commercial!=-1)
set @stemp=@stemp+' and commercialid='+ cast(@Commercial as varchar)



set @stemp =@stemp+ ' and (pid in(select distinct property_id from h_cache where '
if (@Plan!='')
	begin
	set @stemp =@stemp+@Plan+ '  and  '
	end
if (@PriceRange!='')
begin
	declare @MyPriceRange nvarchar(100)

	if (@PriceRange='<=250')
	set @MyPriceRange ='priceNoTax>0 and priceNoTax<= 250'
	if (@PriceRange='250-400')
	set @MyPriceRange ='priceNoTax>250 and priceNoTax<=400'
	if (@PriceRange='400-600')
	set @MyPriceRange ='priceNoTax>400 and priceNoTax<=600'
	if (@PriceRange='600-800')
	set @MyPriceRange ='priceNoTax>600 and priceNoTax<=800'
	if (@PriceRange='>800')
	set @MyPriceRange ='priceNoTax> 800'

	set @stemp =@stemp +@MyPriceRange+' '
	
end
else
begin
set @stemp =@stemp+ '  priceNoTax>0 '
end

set @stemp =@stemp+ '  and avstat!=''N''  and (datediff(hh,getdate(),Availdate)+24>=cutoff)  and  Availdate>= '''+convert(varchar(10),@CheckIn,120)+''' AND Availdate<'''+convert(varchar(10),@CheckOut,120)+''') )'




if (@doCount =0)
begin
set @s =@s+@stemp+ ' order by credit desc, pagerank desc,hotel_id ) as aa  order by credit,pagerank ,hotel_id desc) as aa order by credit desc,pagerank desc,hotel_id'
end
else
set @s =@s+@stemp

exec ( @s )
print @s
go


create procedure dbo.SearchHotelInfo @Title nvarchar(50),
 @City int,
 @District int,
 @Commercial int,
 @CheckIn datetime,
 @CheckOut datetime,
 @PriceRange nvarchar(50),
 @AirPortDistance int,
 @Stars int,
 @hotelGeography nvarchar(2000),
 @AirPortCode nvarchar(50),
 @ConfirmationType nvarchar(50),
 @Plan nvarchar(500), 
 @GroupID nvarchar(2000), 
 @PageSize int=10, 
 @CurPage int=1, 
 @doCount int 
declare @MyTitle nvarchar(50)
    
    set @Title=replace(@Title,'''','''''') 
    set @Title=replace(@Title,'--','') 
    set @Title=replace(@Title,';','') 
set @MyTitle = '%'+@Title+'%'


    
   
   
    



declare @s varchar(6000) 
declare @stemp varchar(6000) 
if (@doCount != 0)  
begin 
set @s ='select count(*) as Total from dbo.Hotel '
end
else
begin
declare @PageIndex int
set @PageIndex=@CurPage*@PageSize
set @s ='select  top ' + cast(@PageSize as nvarchar(20)) + ' * from (select top ' + cast(@PageSize as nvarchar(20)) + ' * from (select top ' +cast(@PageIndex as nvarchar(20)) + ' * from dbo.Hotel '
end

if(@GroupID!='groupid not in ()')
begin
if (@GroupID != '')  
begin 
set @s =@s+' where  passed=1 '+@GroupID
end
end
else
begin
set @s =@s+' where passed=1 '
end

set @stemp =''


if (@Title!='')
set @stemp =@stemp+'and (Title like '''+@MyTitle+''' or Title_e like '''+@MyTitle+''' or keywords like ''%'+@MyTitle+'%'' )'

if (@Stars!=10)
	begin
		if(@Stars=0)
			set @stemp =@stemp+' and (Stars =0 and Diamond=0)'
		else
			set @stemp =@stemp+' and ((Stars ='+ cast(@Stars as varchar)+' and Diamond=0)  or (Diamond='+ cast(@Stars as varchar)+' and Stars=0))'
	end

if (@hotelGeography!='')
set @stemp =@stemp+' and address1 like''%'+@hotelGeography+'%'''

	


	
	
	

if (@City!=-1)
set @stemp=@stemp+' and cityid='+ cast(@City as varchar)

if (@District!=-1)
set @stemp=@stemp+' and districtid='+ cast(@District as varchar)

if (@Commercial!=-1)
set @stemp=@stemp+' and commercialid='+ cast(@Commercial as varchar)



set @stemp =@stemp+ ' and (pid in(select distinct property_id from h_cache where '
if (@Plan!='')
	begin
	set @stemp =@stemp+@Plan+ '  and  '
	end
if (@PriceRange!='')
begin
	declare @MyPriceRange nvarchar(100)

	if (@PriceRange='<=250')
	set @MyPriceRange ='priceNoTax>0 and priceNoTax<= 250'
	if (@PriceRange='250-400')
	set @MyPriceRange ='priceNoTax>250 and priceNoTax<=400'
	if (@PriceRange='400-600')
	set @MyPriceRange ='priceNoTax>400 and priceNoTax<=600'
	if (@PriceRange='600-800')
	set @MyPriceRange ='priceNoTax>600 and priceNoTax<=800'
	if (@PriceRange='>800')
	set @MyPriceRange ='priceNoTax> 800'

	set @stemp =@stemp +@MyPriceRange+' '
	
end
else
begin
set @stemp =@stemp+ '  priceNoTax>0 '
end

set @stemp =@stemp+ '  and avstat!=''N''  and (datediff(hh,getdate(),Availdate)+24>=cutoff)  and  Availdate>= '''+convert(varchar(10),@CheckIn,120)+''' AND Availdate<'''+convert(varchar(10),@CheckOut,120)+''') )'





print(@stemp)
print(@s)
if (@doCount =0)
begin
set @s =@s+@stemp+ ' order by credit desc, pagerank desc,hotel_id ) as aa  order by credit,pagerank ,hotel_id desc) as aa order by credit desc,pagerank desc,hotel_id'
end
else
set @s =@s+@stemp

exec ( @s )
print @s
go


create procedure dbo.SearchHotelNews @Title nvarchar(50),
 @City int,
 @District int,
 @Commercial int,
 @CheckIn datetime,
 @CheckOut datetime,
 @price varchar(200),
 @MinStar nvarchar(50),
 @Maxstar nvarchar(50),
 @hotelGeography nvarchar(2000),
 @ConfirmationType nvarchar(50),
 @Plan nvarchar(500), 
 @GroupID nvarchar(2000), 
 @PageSize int=10, 
 @CurPage int=1, 
 @doCount int 
declare @MyTitle nvarchar(50)
    
    set @Title=replace(@Title,'''','''''') 
    set @Title=replace(@Title,'--','') 
    set @Title=replace(@Title,';','') 
set @MyTitle = '%'+@Title+'%'


    
   
   
    



declare @s varchar(6000) 
declare @stemp varchar(6000) 
if (@doCount != 0)  
begin 
set @s ='select count(*) as Total from dbo.Hotel '
end
else
begin
declare @PageIndex int
set @PageIndex=@CurPage*@PageSize
set @s ='select  top ' + cast(@PageSize as nvarchar(20)) + ' * from (select top ' + cast(@PageSize as nvarchar(20)) + ' * from (select top ' +cast(@PageIndex as nvarchar(20)) + ' * from dbo.Hotel '
end

if (@GroupID != '')  
begin 
set @s =@s+' where  passed=1 and  '+@GroupID
end
else
begin
set @s =@s+' where passed=1 '
end

set @stemp =''


if (@Title!='')
begin
set @stemp =@stemp+'and (Title like '''+@MyTitle+''' or Title_e like '''+@MyTitle+''' or keywords like ''%'+@MyTitle+'%'' )'
end


if(@Maxstar!='0')
begin
set @stemp =@stemp+' and ((Stars >='+ cast(@MinStar as varchar)+' or Diamond>='+ cast(@MinStar as varchar)+')'+' and (Stars <='+ cast(@Maxstar as varchar)+' or Diamond<='+ cast(@Maxstar as varchar)+'))'
end



if (@hotelGeography!='')
set @stemp =@stemp+' and address1 like''%'+@hotelGeography+'%'''

	


	
	
	

if (@City!=-1)
set @stemp=@stemp+' and cityid='+ cast(@City as varchar)

if (@District!=-1)
set @stemp=@stemp+' and districtid='+ cast(@District as varchar)

if (@Commercial!=-1)
set @stemp=@stemp+' and commercialid='+ cast(@Commercial as varchar)



set @stemp =@stemp+ ' and (pid in(select distinct property_id from h_cache where '
if (@Plan!='')
	begin
	set @stemp =@stemp+@Plan
	end







set @stemp =@stemp+@price


set @stemp =@stemp+ '  and avstat!=''N''  and (datediff(hh,getdate(),Availdate)+24>=cutoff)  and  Availdate>= '''+convert(varchar(10),@CheckIn,120)+''' AND Availdate<'''+convert(varchar(10),@CheckOut,120)+''') )'




if (@doCount =0)
begin
set @s =@s+@stemp+ ' order by credit desc, pagerank desc,hotel_id ) as aa  order by credit,pagerank ,hotel_id desc) as aa order by credit desc,pagerank desc,hotel_id'
end
else
set @s =@s+@stemp

exec ( @s )
print @s
go


create procedure dbo.SearchHotel_Custom (
 	@Title nvarchar(50),
 	@City int,
 	@District int,
 	@Commercial int,
 	@PriceRange nvarchar(50),
 	@AirPortDistance int,
 	@Stars int,
 	@corp int,
 	@flag int,
 	@hotelGeography nvarchar(2000),
 	@AirPortCode nvarchar(50),
 	@ConfirmationType nvarchar(50),
 	@Plan nvarchar(500), 
 	@GroupID nvarchar(500), 
 	@PageSize int=10, 
 	@CurPage int=1, 
 	@doCount int 
 ) as
declare @MyTitle nvarchar(50)
    
    set @Title=replace(@Title,'''','''''') 
    set @Title=replace(@Title,'--','') 
    set @Title=replace(@Title,';','') 
    
set @MyTitle = '%'+@Title+'%'


    
   
   
    



declare @s varchar(6000) 
declare @stemp varchar(6000)

if (@doCount != 0)  
	begin 
		set @s ='select count(*) as Total from dbo.Hotel '
	end
else
	begin
		declare @PageIndex int
		set @PageIndex=@CurPage*@PageSize
		set @s ='select top ' + cast(@PageSize as nvarchar(20)) + ' * from (select top ' + cast(@PageSize as nvarchar(20)) + ' * from (select top ' +cast(@PageIndex as nvarchar(20)) + ' * from dbo.Hotel '
	end

if (@GroupID != '')  
	begin 
		set @s =@s+' where '+@GroupID
	end
else
	begin
		set @s =@s+' where 1=1 '
	end

set @stemp =''


if (@Title!='')
	set @stemp =@stemp+'and (Title like '''+@MyTitle+''' or Title_e like '''+@MyTitle+''' or keywords like ''%'+@MyTitle+'%'' )'

if (@Stars!=10)
	set @stemp =@stemp+' and (Stars ='+ cast(@Stars as varchar)+' or Diamond='+ cast(@Stars as varchar)+')'


if (@hotelGeography!='')
	set @stemp =@stemp+' and address1 like''%'+@hotelGeography+'%'''

	


	
	
	

if (@City!=-1)
	set @stemp=@stemp+' and cityid='+ cast(@City as varchar)

if (@District!=-1)
	set @stemp=@stemp+' and districtid='+ cast(@District as varchar)

if (@Commercial!=-1)
	set @stemp=@stemp+' and commercialid='+ cast(@Commercial as varchar)



set @stemp =@stemp+ ' and (pid in(select distinct property_id from h_cache where '
if (@Plan!='')
	begin
		set @stemp =@stemp+@Plan+ '  and  '
	end
if (@PriceRange!='')
	begin
		declare @MyPriceRange nvarchar(100)

		if (@PriceRange = '<=250')
			set @MyPriceRange ='priceNoTax>0 and priceNoTax<= 250'
		if (@PriceRange = '250-400')
			set @MyPriceRange ='priceNoTax>250 and priceNoTax<=400'
		if (@PriceRange = '400-600')
			set @MyPriceRange ='priceNoTax>400 and priceNoTax<=600'
		if (@PriceRange = '600-800')
			set @MyPriceRange ='priceNoTax>600 and priceNoTax<=800'
		if (@PriceRange = '>800')
			set @MyPriceRange ='priceNoTax > 800'

		set @stemp =@stemp + @MyPriceRange + ' '
		
	end
else
	begin
		set @stemp =@stemp+ '  priceNoTax>0 '
	end

set @stemp =@stemp+ '  and avstat!=''N'')'



if(@corp!='')
	begin
		declare @MyCorp varchar(8000)

		select @mycorp=case when customhotel is null or len(customhotel)<1 then '0' else  left(customhotel,len(customhotel)-1) end from corp where corp_id=@corp


			   

		if(@flag=0)
			begin
				select  @mycorp='and (pid not in(select pid from hotel where Hotel_ID in('+@mycorp+')'
			end

		if(@flag=1)
			begin
				select  @mycorp='and (pid in(select pid from hotel where Hotel_ID in('+@mycorp+')'
			end

		
		
		set @stemp=@stemp+@mycorp
		set @stemp=@stemp+')))'
	end






if (@doCount = 0)
	begin
		set @s =@s+@stemp+ ' order by pagerank desc,hotel_id ) as aa  order by pagerank ,hotel_id desc) as aa order by pagerank desc,hotel_id'
	end
else
	set @s =@s+@stemp


exec ( @s )
	
print @s
go


create procedure dbo.SearchHotel_FITOVS_Hotel @Title nvarchar(50),
 @City int,
 @CheckIn datetime,
 @CheckOut datetime,
 @Stars nvarchar(100),
 @Plan nvarchar(500), 
 @GroupID nvarchar(500), 
 @PageSize int=10, 
 @CurPage int=1, 
 @doCount int 
declare @MyTitle nvarchar(50)
    
    set @Title=replace(@Title,'''','''''') 
    set @Title=replace(@Title,'--','') 
    set @Title=replace(@Title,';','') 
set @MyTitle = '%'+@Title+'%'

declare @s varchar(6000) 
declare @stemp varchar(6000) 
if (@doCount != 0)  
begin 
set @s ='select count(*) as Total from dbo.Hotel '
end
else
begin
declare @PageIndex int
set @PageIndex=@CurPage*@PageSize
set @s ='select  top ' + cast(@PageSize as nvarchar(20)) + ' * from (select top ' + cast(@PageSize as nvarchar(20)) + ' * from (select top ' +cast(@PageIndex as nvarchar(20)) + ' * from dbo.Hotel '
end

if (@GroupID != '')  
begin 
set @s =@s+' where Passed=1 and  '+@GroupID+' '
end
else
begin
set @s =@s+' where Passed=1 '
end

set @stemp =''


if (@Title!='')
set @stemp =@stemp+'and (Title like '''+@MyTitle+''' or Title_e like '''+@MyTitle+''' or keywords like ''%'+@MyTitle+'%'' )'

if (@Stars!='10')
set @stemp =@stemp+' and stars='+@Stars	

if (@City!=-1)
set @stemp=@stemp+' and cityid='+ cast(@City as varchar)

set @stemp =@stemp+ ' and (pid in(select distinct property_id from h_cache where 1=1 '
declare @ptemp varchar(6000) 
set @ptemp =' select property_id, min(pricenotax) as minPrice from h_cache where  1=1 '
if (@Plan!='')
	begin
	set @stemp = @stemp+'  and  '+@Plan
	set @ptemp = @ptemp+'  and  '+@Plan
	end


set @stemp =@stemp+ '  and avstat!=''N''  and (datediff(hh,getdate(),Availdate)+24>=cutoff)  and  Availdate>= '''+convert(varchar(10),@CheckIn,120)+''' AND Availdate<'''+convert(varchar(10),@CheckOut,120)+''') )'
set @ptemp =@ptemp+ '  and avstat!=''N''  and (datediff(hh,getdate(),Availdate)+24>=cutoff)  and  Availdate>= '''+convert(varchar(10),@CheckIn,120)+''' AND Availdate<'''+convert(varchar(10),@CheckOut,120)+''''



if (@doCount =0)
begin
set @s =@s+@stemp+ ' order by pagerank desc,hotel_id ) as aa  order by pagerank ,hotel_id desc) as aa order by pagerank desc,hotel_id'
set @ptemp =@ptemp+' group by property_id '
set @s='select P.minPrice,H.*,D.Amenities  from ('+@s+') H left join ('+@ptemp+') P on H.pid = P.property_id left join H_description  D on H.pid=D.property_id and d.languagetype=0 '
end
else
set @s =@s+@stemp
print @S
exec ( @s )
go


create procedure dbo.SearchHotel_FIT_Hotel @Title nvarchar(50),
 @City int,
 @District nvarchar(4000),
 @Commercial nvarchar(4000),
 @CheckIn datetime,
 @CheckOut datetime,
 @PriceRange nvarchar(50),
 @AirPortDistance int,
 @Stars nvarchar(100),
 @hotelGeography nvarchar(2000),
 @AirPortCode nvarchar(50),
 @ConfirmationType nvarchar(50),
 @Plan nvarchar(500), 
 @GroupID nvarchar(500), 
 @PageSize int=10, 
 @CurPage int=1, 
 @doCount int 
declare @MyTitle nvarchar(50)
    
    set @Title=replace(@Title,'''','''''') 
    set @Title=replace(@Title,'--','') 
    set @Title=replace(@Title,';','') 
set @MyTitle = '%'+@Title+'%'


    
   
   
    



declare @s varchar(6000) 
declare @stemp varchar(6000) 
if (@doCount != 0)  
begin 
set @s ='select count(*) as Total from dbo.Hotel '
end
else
begin
declare @PageIndex int
set @PageIndex=@CurPage*@PageSize
set @s ='select  top ' + cast(@PageSize as nvarchar(20)) + ' * from (select top ' + cast(@PageSize as nvarchar(20)) + ' * from (select top ' +cast(@PageIndex as nvarchar(20)) + ' * from dbo.Hotel '
end

if (@GroupID != '')  
begin 
set @s =@s+' where '+@GroupID
end
else
begin
set @s =@s+' where 1=1 '
end

set @stemp =''


if (@Title!='')
set @stemp =@stemp+'and (Title like '''+@MyTitle+''' or Title_e like '''+@MyTitle+''' or keywords like ''%'+@MyTitle+'%'' )'

if (@Stars!='10')
set @stemp =@stemp+' and '+@Stars


if (@hotelGeography!='')
set @stemp =@stemp+' and address1 like''%'+@hotelGeography+'%'''

	


	
	
	

if (@City!=-1)
set @stemp=@stemp+' and cityid='+ cast(@City as varchar)

if (@District!='-1')
set @stemp=@stemp+' and ('+@District



if (@Commercial!='-1')
begin
    if(@District!='-1')
    begin
         set @stemp=@stemp+' or '+ @Commercial+')'  
    end  
    else
    begin
    set @stemp=@stemp+' and('+ @Commercial+')'
    end
end
else
begin
    if(@District!='-1')
   begin
    set @stemp=@stemp+')'
    end
end



set @stemp =@stemp+ ' and (pid in(select distinct property_id from h_cache where '
declare @ptemp varchar(6000) 
set @ptemp =' select property_id, min(pricenotax) as minPrice from h_cache where '
if (@Plan!='')
	begin
	set @stemp =@stemp+@Plan+ '  and  '
	set @ptemp =@ptemp+@Plan+ '  and  '
	end
if (@PriceRange!='')
begin
	declare @MyPriceRange nvarchar(100)

	
	set @MyPriceRange =@PriceRange;
	set @stemp =@stemp +@MyPriceRange+' '
	set @ptemp =@ptemp +@MyPriceRange+' '
end
else
begin
set @stemp =@stemp+ '  priceNoTax>0 '
set @ptemp =@ptemp+ '  priceNoTax>0 '
end

set @stemp =@stemp+ '  and avstat!=''N''  and (datediff(hh,getdate(),Availdate)+24>=cutoff)  and  Availdate>= '''+convert(varchar(10),@CheckIn,120)+''' AND Availdate<'''+convert(varchar(10),@CheckOut,120)+''') )'
set @ptemp =@ptemp+ '  and avstat!=''N''  and (datediff(hh,getdate(),Availdate)+24>=cutoff)  and  Availdate>= '''+convert(varchar(10),@CheckIn,120)+''' AND Availdate<'''+convert(varchar(10),@CheckOut,120)+''''



if (@doCount =0)
begin
set @s =@s+@stemp+ ' order by pagerank desc,hotel_id ) as aa  order by pagerank ,hotel_id desc) as aa order by pagerank desc,hotel_id'
set @ptemp =@ptemp+' group by property_id '
set @s='select P.minPrice,H.*,D.Amenities  from ('+@s+') H left join ('+@ptemp+') P on H.pid = P.property_id left join H_description  D on H.pid=D.property_id and d.languagetype=0 '
end
else
set @s =@s+@stemp



print @s
exec ( @s )
go


create procedure dbo.SearchHotel_QuYu @Title nvarchar(50),
 @City int,
 @District int,
 @Commercial int,
 @CheckIn datetime,
 @CheckOut datetime,
 @PriceRange nvarchar(50),
 @AirPortDistance int,
 @Stars int,
 @hotelGeography nvarchar(2000),
 @AirPortCode nvarchar(50),
 @ConfirmationType nvarchar(50),
 @Plan nvarchar(500), 
 @GroupID nvarchar(2000), 
 @PageSize int=10, 
 @CurPage int=1, 
 @doCount int 
declare @MyTitle nvarchar(50)
    
    set @Title=replace(@Title,'''','''''') 
    set @Title=replace(@Title,'--','') 
    set @Title=replace(@Title,';','') 
set @MyTitle = '%'+@Title+'%'


    
   
   
    



declare @s varchar(6000) 
declare @stemp varchar(6000) 
if (@doCount != 0)  
begin 
set @s ='select count(*) as Total from dbo.Hotel '
end
else
begin
declare @PageIndex int
set @PageIndex=@CurPage*@PageSize
set @s ='select  top ' + cast(@PageSize as nvarchar(20)) + ' * from (select top ' + cast(@PageSize as nvarchar(20)) + ' * from (select top ' +cast(@PageIndex as nvarchar(20)) + ' * from dbo.Hotel '
end

if (@GroupID != '')  
begin 
set @s =@s+' where  passed=1 and  '+@GroupID
end
else
begin
set @s =@s+' where passed=1 '
end

set @stemp =''


if (@Title!='')
set @stemp =@stemp+'and (Title like '''+@MyTitle+''' or Title_e like '''+@MyTitle+''' or keywords like ''%'+@MyTitle+'%'' )'

if (@Stars!=10)
	begin
		if(@Stars=0)
			set @stemp =@stemp+' and (Stars =0 and Diamond=0)'
		else
			set @stemp =@stemp+' and ((Stars ='+ cast(@Stars as varchar)+' and Diamond=0)  or (Diamond='+ cast(@Stars as varchar)+' and Stars=0))'
	end

if (@hotelGeography!='')
set @stemp =@stemp+' and address1 like''%'+@hotelGeography+'%'''

	


	
	
	

if (@City!=-1)
set @stemp=@stemp+' and cityid='+ cast(@City as varchar)

if (@District!=-1)
set @stemp=@stemp+' and districtid='+ cast(@District as varchar)

if (@Commercial!=-1)
set @stemp=@stemp+' and commercialid='+ cast(@Commercial as varchar)



set @stemp =@stemp+ ' and (pid in(select distinct property_id from h_cache where '
if (@Plan!='')
	begin
	set @stemp =@stemp+@Plan+ '  and  '
	end
if (@PriceRange!='')
begin
	declare @MyPriceRange nvarchar(100)

	if (@PriceRange='<=250')
	set @MyPriceRange ='priceNoTax>0 and priceNoTax<= 250'
	if (@PriceRange='250-400')
	set @MyPriceRange ='priceNoTax>250 and priceNoTax<=400'
	if (@PriceRange='400-600')
	set @MyPriceRange ='priceNoTax>400 and priceNoTax<=600'
	if (@PriceRange='600-800')
	set @MyPriceRange ='priceNoTax>600 and priceNoTax<=800'
	if (@PriceRange='>800')
	set @MyPriceRange ='priceNoTax> 800'

	set @stemp =@stemp +@MyPriceRange+' '
	
end
else
begin
set @stemp =@stemp+ '  priceNoTax>0 '
end

set @stemp =@stemp+ '  and avstat!=''N''  and (datediff(hh,getdate(),Availdate)+24>=cutoff)  and  Availdate>= '''+convert(varchar(10),@CheckIn,120)+''' AND Availdate<'''+convert(varchar(10),@CheckOut,120)+''') )'




if (@doCount =0)
begin
set @s =@s+@stemp+ ' order by credit desc, pagerank desc,hotel_id ) as aa  order by credit,pagerank ,hotel_id desc) as aa order by credit desc,pagerank desc,hotel_id'
end
else
set @s =@s+@stemp

exec ( @s )
print @s
go


create procedure dbo.SearchHotel_QuYuDFBnew @Title nvarchar(50),
 @City int,
 @District int,
 @Commercial int,
 @CheckIn datetime,
 @CheckOut datetime,
 @PriceRange nvarchar(50),
 @AirPortDistance int,
 @Stars int,
 @hotelGeography nvarchar(2000),
 @AirPortCode nvarchar(50),
 @ConfirmationType nvarchar(50),
 @Plan nvarchar(500), 
 @GroupID nvarchar(2000), 
 @PageSize int=10, 
 @CurPage int=1, 
 @doCount int 
declare @MyTitle nvarchar(50)
    
    set @Title=replace(@Title,'''','''''') 
    set @Title=replace(@Title,'--','') 
    set @Title=replace(@Title,';','') 
set @MyTitle = '%'+@Title+'%'


    
   
   
    



declare @s varchar(6000) 
declare @stemp varchar(6000) 
if (@doCount != 0)  
begin 
set @s ='select count(*) as Total from dbo.Hotel '
end
else
begin
declare @PageIndex int
set @PageIndex=@CurPage*@PageSize
set @s ='select  top ' + cast(@PageSize as nvarchar(20)) + ' * from (select top ' + cast(@PageSize as nvarchar(20)) + ' * from (select top ' +cast(@PageIndex as nvarchar(20)) + ' * from dbo.Hotel '
end

if(@GroupID!='groupid not in ()')
begin
if (@GroupID != '')  
begin 
set @s =@s+' where  passed=1 '+@GroupID
end
end
else
begin
set @s =@s+' where passed=1 '
end

set @stemp =''


if (@Title!='')
set @stemp =@stemp+'and (Title like '''+@MyTitle+''' or Title_e like '''+@MyTitle+''' or keywords like ''%'+@MyTitle+'%'' )'

if (@Stars!=10)
	begin
		if(@Stars=0)
			set @stemp =@stemp+' and (Stars =0 and Diamond=0)'
		else
			set @stemp =@stemp+' and ((Stars ='+ cast(@Stars as varchar)+' and Diamond=0)  or (Diamond='+ cast(@Stars as varchar)+' and Stars=0))'
	end

if (@hotelGeography!='')
set @stemp =@stemp+' and address1 like''%'+@hotelGeography+'%'''

	


	
	
	

if (@City!=-1)
set @stemp=@stemp+' and cityid='+ cast(@City as varchar)

if (@District!=-1)
set @stemp=@stemp+' and districtid='+ cast(@District as varchar)

if (@Commercial!=-1)
set @stemp=@stemp+' and commercialid='+ cast(@Commercial as varchar)



set @stemp =@stemp+ ' and (pid in(select distinct property_id from h_cache where '
if (@Plan!='')
	begin
	set @stemp =@stemp+@Plan+ '  and  '
	end
if (@PriceRange!='')
begin
	declare @MyPriceRange nvarchar(100)

	if (@PriceRange='<=250')
	set @MyPriceRange ='priceNoTax>0 and priceNoTax<= 250'
	if (@PriceRange='250-400')
	set @MyPriceRange ='priceNoTax>250 and priceNoTax<=400'
	if (@PriceRange='400-600')
	set @MyPriceRange ='priceNoTax>400 and priceNoTax<=600'
	if (@PriceRange='600-800')
	set @MyPriceRange ='priceNoTax>600 and priceNoTax<=800'
	if (@PriceRange='>800')
	set @MyPriceRange ='priceNoTax> 800'

	set @stemp =@stemp +@MyPriceRange+' '
	
end
else
begin
set @stemp =@stemp+ '  priceNoTax>0 '
end

set @stemp =@stemp+ '  and avstat!=''N''  and (datediff(hh,getdate(),Availdate)+24>=cutoff)  and  Availdate>= '''+convert(varchar(10),@CheckIn,120)+''' AND Availdate<'''+convert(varchar(10),@CheckOut,120)+''') )'





if (@doCount =0)
begin
set @s =@s+@stemp+ ' order by credit desc, pagerank desc,hotel_id ) as aa  order by credit,pagerank ,hotel_id desc) as aa order by credit desc,pagerank desc,hotel_id'
end
else
set @s =@s+@stemp

exec ( @s )
print @s
go


create procedure dbo.SearchHotel_QuYuFIT_City @Title nvarchar(50),
 @City int,
 @District nvarchar(4000),
 @Commercial nvarchar(4000),
 @CheckIn datetime,
 @CheckOut datetime,
 @PriceRange nvarchar(50),
 @AirPortDistance int,
 @minStars float,
 @maxStars float,
 @hotelGeography nvarchar(2000),
 @AirPortCode nvarchar(50),
 @ConfirmationType nvarchar(50),
 @Plan nvarchar(500), 
 @GroupID nvarchar(500), 
 @PageSize int=10, 
 @CurPage int=1, 
 @doCount int 
declare @MyTitle nvarchar(50)
    
    set @Title=replace(@Title,'''','''''') 
    set @Title=replace(@Title,'--','') 
    set @Title=replace(@Title,';','') 
set @MyTitle = '%'+@Title+'%'


    
   
   
    



declare @s varchar(6000) 
declare @stemp varchar(6000) 
if (@doCount != 0)  
begin 
set @s ='select count(*) as Total from dbo.Hotel '
end
else
begin
declare @PageIndex int
set @PageIndex=@CurPage*@PageSize
set @s ='select  top ' + cast(@PageSize as nvarchar(20)) + ' * from (select top ' + cast(@PageSize as nvarchar(20)) + ' * from (select top ' +cast(@PageIndex as nvarchar(20)) + ' * from dbo.Hotel '
end

if (@GroupID != '')  
begin 
set @s =@s+' where '+@GroupID
end
else
begin
set @s =@s+' where 1=1 '
end

set @stemp =''


if (@Title!='')
set @stemp =@stemp+'and (Title like '''+@MyTitle+''' or Title_e like '''+@MyTitle+''' or keywords like ''%'+@MyTitle+'%'' )'



set @stemp =@stemp+' and Stars >='+ cast(@minStars as varchar)
set @stemp =@stemp+' and Stars <='+ cast(@maxStars as varchar)

if (@hotelGeography!='')
set @stemp =@stemp+' and address1 like''%'+@hotelGeography+'%'''

	


	
	
	

if (@City!=-1)
set @stemp=@stemp+' and cityid='+ cast(@City as varchar)

if (@District!=-1)
set @stemp=@stemp+' and ('+@District+')'


if (@Commercial!=-1)
set @stemp=@stemp+' and ('+@Commercial+')'




set @stemp =@stemp+ ' and (pid in(select distinct property_id from h_cache where '
declare @ptemp varchar(6000) 
set @ptemp =' select property_id, min(pricenotax) as minPrice from h_cache where '
if (@Plan!='')
	begin
	set @stemp =@stemp+@Plan+ '  and  '
	set @ptemp =@ptemp+@Plan+ '  and  '
	end
if (@PriceRange!='')
begin
	declare @MyPriceRange nvarchar(100)

	if (@PriceRange='<=250')
	set @MyPriceRange ='priceNoTax>0 and priceNoTax<= 250'
	if (@PriceRange='250-400')
	set @MyPriceRange ='priceNoTax>250 and priceNoTax<=400'
	if (@PriceRange='400-600')
	set @MyPriceRange ='priceNoTax>400 and priceNoTax<=600'
	if (@PriceRange='600-800')
	set @MyPriceRange ='priceNoTax>600 and priceNoTax<=800'
	if (@PriceRange='>800')
	set @MyPriceRange ='priceNoTax> 800'

	set @stemp =@stemp +@MyPriceRange+' '
	set @ptemp =@ptemp +@MyPriceRange+' '
end
else
begin
set @stemp =@stemp+ '  priceNoTax>0 '
set @ptemp =@ptemp+ '  priceNoTax>0 '
end

set @stemp =@stemp+ '  and avstat!=''N''  and (datediff(hh,getdate(),Availdate)+24>=cutoff)  and  Availdate>= '''+convert(varchar(10),@CheckIn,120)+''' AND Availdate<'''+convert(varchar(10),@CheckOut,120)+''') )'
set @ptemp =@ptemp+ '  and avstat!=''N''  and (datediff(hh,getdate(),Availdate)+24>=cutoff)  and  Availdate>= '''+convert(varchar(10),@CheckIn,120)+''' AND Availdate<'''+convert(varchar(10),@CheckOut,120)+''''



if (@doCount =0)
begin
set @s =@s+@stemp+ ' order by pagerank desc,hotel_id ) as aa  order by pagerank ,hotel_id desc) as aa order by pagerank desc,hotel_id'
set @ptemp =@ptemp+' group by property_id '
set @s='select P.minPrice,H.*,D.Amenities  from ('+@s+') H left join ('+@ptemp+') P on H.pid = P.property_id left join H_description  D on H.pid=D.property_id and d.languagetype=0 '
end
else
set @s =@s+@stemp



print @s
exec ( @s )
go


create procedure dbo.SelectCXL @Property_id int,
 @Languagetype int,
 @Rule nvarchar(50) as
select * from H_cxlrule where Property_id=@Property_id and [Rule]=@Rule and languagetype=@Languagetype
go


create procedure dbo.SelectGUA @Property_id int,
 @Languagetype int,
 @Grule nvarchar(50) as
select * from H_guarule where property_id=@Property_id and Grule=@Grule and languagetype=@Languagetype
go


create procedure dbo.SelectTAX (
 	@Property_id int,
 	@languagetype int
 	) as
select * from H_tax where property_id=@Property_id and languagetype=@languagetype
go


create procedure dbo.SelectTAXDFB <@arg> <type> as
declare <@var> <type>
begin

end
go


create procedure dbo.SetFIT_Profile @ApplicationName      nvarchar(256),
 	@UserName             nvarchar(256),
 	@IsUserAnonymous	  bit,
 	@FirstName            nvarchar(100) ,
 	@LastName             nvarchar(100),
 	@MobilePhone          varchar(50)  ,
 	@Phone                varchar(50)  ,
 	@Address              nvarchar(200),
 	@LogTimes             int          ,
 	@LastIP               varchar(24) as
declare	@ApplicationId uniqueidentifier
set		@ApplicationId = NULL

declare @CurrentUtcDate datetime
set     @CurrentUtcDate = getutcdate()

exec dbo.aspnet_Applications_CreateApplication @ApplicationName, @ApplicationId OUTPUT

declare @UserId uniqueidentifier

select	@UserId = UserId
from	dbo.vw_aspnet_Users
where	ApplicationId	= @ApplicationId
and		LoweredUserName = LOWER(@UserName)

if(@UserId IS NULL)
	exec dbo.aspnet_Users_CreateUser @ApplicationId, @UserName, @IsUserAnonymous, @CurrentUtcDate, @UserId OUTPUT


if exists (select 1 from dbo.FIT_Profile where UserId = @UserId) 
BEGIN 
	update dbo.FIT_Profile
	set	FirstName=@FirstName,
		LastName=@LastName,
		MobilePhone=@MobilePhone,
		Phone=@Phone,
		Address=@Address,
		LogTimes=@LogTimes,
		LastIP=@LastIP,
		LastUpdatedDate	= @CurrentUtcDate
	where UserId = @UserId
END
else
BEGIN
	insert dbo.FIT_Profile (UserId,FirstName,LastName,MobilePhone,Phone,Address,LogTimes,LastIP, LastUpdatedDate)
    values (@UserId,@FirstName,@LastName,@MobilePhone,@Phone,@Address,@LogTimes,@LastIP, @CurrentUtcDate)
END
go


create procedure dbo.Set_FIT_CityKeyWords @CityID as
int ,@keywords as nvarchar(50),@type as int
as
begin
update FIT_CityKeyWords set times=times+1 where keywords=@keywords and  type=@type and cityID=@CityID
if @@rowcount=0
begin
insert FIT_CityKeyWords([CityID], [Keywords], [type])
values(@CityID,@keywords,@type);
end
end
go


create procedure dbo.UserDemo (
  @sqlwhere varchar(100)
 ) as
declare @sqlstr varchar(6000);
set @sqlStr='select * from [user] where'+ @sqlwhere
print @sqlStr
exec(@sqlStr)
go


create procedure dbo.User_Add @username nvarchar(50),
 
 @UserPassword nvarchar(50),
 
 @Email nvarchar(255),
 
 @address nvarchar(255),
 
 @tel nvarchar(50),
 
 @firstname nvarchar(50),
 
 @lastname nvarchar(50),
 
 @parentid int,
 
 @remark varchar(500),
 
 @userlevel int,
 
 @booktimes int,
 
 @totalmount decimal(19,2),
 
 @roomnights int,
 
 @usertype nvarchar(50),
 
 @congeal int as
set @userlevel=@userlevel

insert into [user](username,UserPassword,Email,address,tel,firstname,lastname,parentid,remark,userlevel,booktimes,totalmount,roomnights,usertype,congeal)

values(@username,@UserPassword,@Email,@address,@tel,@firstname,@lastname,@parentid,@remark,@userlevel,@booktimes,@totalmount,@roomnights,@usertype,@congeal)
go


create procedure dbo.air_chinapay @verifyno nvarchar(50),
 @payamount nvarchar(50),
 @paydatetime datetime as
declare @payno nvarchar(50) 


set @payno=dbo.Pay_GetChinaPay_BillNO(getdate(),'00949')
insert into pay(confnum,billno,payman,status,paytimebegin,payamount,currency) values(@verifyno,@payno,'chinapay',0,@paydatetime,@payamount,'156')
if @@RowCount=1
select @payno
else
select ''
go


create procedure dbo.air_chinapayreturn (
 @payno nvarchar(50),
 @paystatus int
 ) as
declare @status int
declare @returnstatus nvarchar(50)


if(exists(select * from pay where billno = @payno and status = 0))
begin
update pay set status=@paystatus,paytimeend=getdate() where billno=@payno and status=0
end


if(exists(select * from pay where billno=@payno and status = 1 ))
	select @returnstatus = "1"
else
	select @returnstatus = "0"

select @returnstatus
go


create procedure dbo.andy_test as
BEGIN
	
	
	select * from air_booklog
END
go


create procedure dbo.chooseSendMessage @err int as
BEGIN TRANSACTION

select * from 
(select distinct content, orig_mobile from sms_send where status=0 and feecode<@err) a 
where not exists
(
select * from 
(select distinct content, orig_mobile from sms_send where status=1) b 
where b.content = a.content and a.orig_mobile = b.orig_mobile

)



COMMIT TRANSACTION
go


create procedure dbo.dt_adduserobject_vcs @vchProperty varchar(64) as
set nocount on

declare @iReturn int
    
    begin transaction
        select @iReturn = objectid from dbo.dtproperties where property = @vchProperty
        if @iReturn IS NULL
        begin
            insert dbo.dtproperties (property) VALUES (@vchProperty)
            update dbo.dtproperties set objectid=@@identity
                    where id=@@identity and property=@vchProperty
            select @iReturn = @@identity
        end
    commit
    return @iReturn
go


create procedure dbo.dt_displayoaerror @iObject int,
     @iresult int as
set nocount on

declare @vchOutput      varchar(255)
declare @hr             int
declare @vchSource      varchar(255)
declare @vchDescription varchar(255)

    exec @hr = master.dbo.sp_OAGetErrorInfo @iObject, @vchSource OUT, @vchDescription OUT

    select @vchOutput = @vchSource + ': ' + @vchDescription
    raiserror (@vchOutput,16,-1)

    return
go


create procedure dbo.dt_setpropertybyid @id int,
 	@property varchar(64),
 	@value varchar(255),
 	@lvalue image as
set nocount on
	declare @uvalue nvarchar(255) 
	set @uvalue = convert(nvarchar(255), @value) 
	if exists (select * from dbo.dtproperties 
			where objectid=@id and property=@property)
	begin
		--
		
		--
		update dbo.dtproperties set value=@value, uvalue=@uvalue, lvalue=@lvalue, version=version+1
			where objectid=@id and property=@property
	end
	else
	begin
		--
		
		--
		insert dbo.dtproperties (property, objectid, value, uvalue, lvalue)
			values (@property, @id, @value, @uvalue, @lvalue)
	end
go


create procedure dbo.dt_addtosourcecontrol @vchSourceSafeINI varchar(255) = '',
     @vchProjectName   varchar(255) ='',
     @vchComment       varchar(255) ='',
     @vchLoginName     varchar(255) ='',
     @vchPassword      varchar(255) ='' as
set nocount on

declare @iReturn int
declare @iObjectId int
select @iObjectId = 0

declare @iStreamObjectId int
select @iStreamObjectId = 0

declare @VSSGUID varchar(100)
select @VSSGUID = 'SQLVersionControl.VCS_SQL'

declare @vchDatabaseName varchar(255)
select @vchDatabaseName = db_name()

declare @iReturnValue int
select @iReturnValue = 0

declare @iPropertyObjectId int
declare @vchParentId varchar(255)

declare @iObjectCount int
select @iObjectCount = 0

    exec @iReturn = master.dbo.sp_OACreate @VSSGUID, @iObjectId OUT
    if @iReturn <> 0 GOTO E_OAError


    
    exec @iReturn = master.dbo.sp_OAMethod @iObjectId,
											'AddProjectToSourceSafe',
											NULL,
											@vchSourceSafeINI,
											@vchProjectName output,
											@@SERVERNAME,
											@vchDatabaseName,
											@vchLoginName,
											@vchPassword,
											@vchComment


    if @iReturn <> 0 GOTO E_OAError

    

    begin tran SetProperties

    

    exec @iPropertyObjectId = dbo.dt_adduserobject_vcs 'VCSProjectID'

    select @vchParentId = CONVERT(varchar(255),@iPropertyObjectId)

    exec dbo.dt_setpropertybyid @iPropertyObjectId, 'VCSProjectID', @vchParentId , NULL
    exec dbo.dt_setpropertybyid @iPropertyObjectId, 'VCSProject' , @vchProjectName , NULL
    exec dbo.dt_setpropertybyid @iPropertyObjectId, 'VCSSourceSafeINI' , @vchSourceSafeINI , NULL
    exec dbo.dt_setpropertybyid @iPropertyObjectId, 'VCSSQLServer', @@SERVERNAME, NULL
    exec dbo.dt_setpropertybyid @iPropertyObjectId, 'VCSSQLDatabase', @vchDatabaseName, NULL

    if @@error <> 0 GOTO E_General_Error

    commit tran SetProperties
    
    select @iObjectCount = 0;

CleanUp:
    select @vchProjectName
    select @iObjectCount
    return

E_General_Error:
    
    goto CleanUp

E_OAError:
    exec dbo.dt_displayoaerror @iObjectId, @iReturn
    goto CleanUp
go


create procedure dbo.dt_addtosourcecontrol_u @vchSourceSafeINI nvarchar(255) = '',
     @vchProjectName   nvarchar(255) ='',
     @vchComment       nvarchar(255) ='',
     @vchLoginName     nvarchar(255) ='',
     @vchPassword      nvarchar(255) ='' as
set nocount on
	exec dbo.dt_addtosourcecontrol 
		@vchSourceSafeINI, 
		@vchProjectName, 
		@vchComment, 
		@vchLoginName, 
		@vchPassword
go


create procedure dbo.dt_adduserobject as
set nocount on
	
	begin transaction
		insert dbo.dtproperties (property) VALUES ('DtgSchemaOBJECT')
		update dbo.dtproperties set objectid=@@identity 
			where id=@@identity and property='DtgSchemaOBJECT'
	commit
	return @@identity
go


create procedure dbo.dt_getpropertiesbyid_vcs @id       int,
     @property varchar(64),
     @value    varchar(255) = NULL OUT as
set nocount on

    select @value = (
        select value
                from dbo.dtproperties
                where @id=objectid and @property=property
                )
go


create procedure dbo.dt_checkinobject @chObjectType  char(4),
     @vchObjectName varchar(255),
     @vchComment    varchar(255)='',
     @vchLoginName  varchar(255),
     @vchPassword   varchar(255)='',
     @iVCSFlags     int = 0,
     @iActionFlag   int = 0,   
     @txStream1     Text = '', 
     @txStream2     Text = '', 
     @txStream3     Text = ''   as
set nocount on

	declare @iReturn int
	declare @iObjectId int
	select @iObjectId = 0
	declare @iStreamObjectId int

	declare @VSSGUID varchar(100)
	select @VSSGUID = 'SQLVersionControl.VCS_SQL'

	declare @iPropertyObjectId int
	select @iPropertyObjectId  = 0

    select @iPropertyObjectId = (select objectid from dbo.dtproperties where property = 'VCSProjectID')

    declare @vchProjectName   varchar(255)
    declare @vchSourceSafeINI varchar(255)
    declare @vchServerName    varchar(255)
    declare @vchDatabaseName  varchar(255)
    declare @iReturnValue	  int
    declare @pos			  int
    declare @vchProcLinePiece varchar(255)

    
    exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSProject',       @vchProjectName   OUT
    exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSourceSafeINI', @vchSourceSafeINI OUT
    exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSQLServer',     @vchServerName    OUT
    exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSQLDatabase',   @vchDatabaseName  OUT

    if @chObjectType = 'PROC'
    begin
        if @iActionFlag = 1
        begin
            

            begin tran compile_all

            
            exec (@txStream1)
            if @@error <> 0 GOTO E_Compile_Fail

            exec (@txStream2)
            if @@error <> 0 GOTO E_Compile_Fail

            exec (@txStream3)
            if @@error <> 0 GOTO E_Compile_Fail
        end

        exec @iReturn = master.dbo.sp_OACreate @VSSGUID, @iObjectId OUT
        if @iReturn <> 0 GOTO E_OAError

        exec @iReturn = master.dbo.sp_OAGetProperty @iObjectId, 'GetStreamObject', @iStreamObjectId OUT
        if @iReturn <> 0 GOTO E_OAError
        
        if @iActionFlag = 1
        begin
            
            declare @iStreamLength int
			
			select @pos=1
			select @iStreamLength = datalength(@txStream2)
			
			if @iStreamLength > 0
			begin
			
				while @pos < @iStreamLength
				begin
						
					select @vchProcLinePiece = substring(@txStream2, @pos, 255)
					
					exec @iReturn = master.dbo.sp_OAMethod @iStreamObjectId, 'AddStream', @iReturnValue OUT, @vchProcLinePiece
            		if @iReturn <> 0 GOTO E_OAError
            		
					select @pos = @pos + 255
					
				end
            
				exec @iReturn = master.dbo.sp_OAMethod @iObjectId,
														'CheckIn_StoredProcedure',
														NULL,
														@sProjectName = @vchProjectName,
														@sSourceSafeINI = @vchSourceSafeINI,
														@sServerName = @vchServerName,
														@sDatabaseName = @vchDatabaseName,
														@sObjectName = @vchObjectName,
														@sComment = @vchComment,
														@sLoginName = @vchLoginName,
														@sPassword = @vchPassword,
														@iVCSFlags = @iVCSFlags,
														@iActionFlag = @iActionFlag,
														@sStream = ''
                                        
			end
        end
        else
        begin
        
            select colid, text into #ProcLines
            from syscomments
            where id = object_id(@vchObjectName)
            order by colid

            declare @iCurProcLine int
            declare @iProcLines int
            select @iCurProcLine = 1
            select @iProcLines = (select count(*) from #ProcLines)
            while @iCurProcLine <= @iProcLines
            begin
                select @pos = 1
                declare @iCurLineSize int
                select @iCurLineSize = len((select text from #ProcLines where colid = @iCurProcLine))
                while @pos <= @iCurLineSize
                begin                
                    select @vchProcLinePiece = convert(varchar(255),
                        substring((select text from #ProcLines where colid = @iCurProcLine),
                                  @pos, 255 ))
                    exec @iReturn = master.dbo.sp_OAMethod @iStreamObjectId, 'AddStream', @iReturnValue OUT, @vchProcLinePiece
                    if @iReturn <> 0 GOTO E_OAError
                    select @pos = @pos + 255                  
                end
                select @iCurProcLine = @iCurProcLine + 1
            end
            drop table #ProcLines

            exec @iReturn = master.dbo.sp_OAMethod @iObjectId,
													'CheckIn_StoredProcedure',
													NULL,
													@sProjectName = @vchProjectName,
													@sSourceSafeINI = @vchSourceSafeINI,
													@sServerName = @vchServerName,
													@sDatabaseName = @vchDatabaseName,
													@sObjectName = @vchObjectName,
													@sComment = @vchComment,
													@sLoginName = @vchLoginName,
													@sPassword = @vchPassword,
													@iVCSFlags = @iVCSFlags,
													@iActionFlag = @iActionFlag,
													@sStream = ''
        end

        if @iReturn <> 0 GOTO E_OAError

        if @iActionFlag = 1
        begin
            commit tran compile_all
            if @@error <> 0 GOTO E_Compile_Fail
        end

    end

CleanUp:
	return

E_Compile_Fail:
	declare @lerror int
	select @lerror = @@error
	rollback tran compile_all
	RAISERROR (@lerror,16,-1)
	goto CleanUp

E_OAError:
	if @iActionFlag = 1 rollback tran compile_all
	exec dbo.dt_displayoaerror @iObjectId, @iReturn
	goto CleanUp
go


create procedure dbo.dt_checkinobject_u @chObjectType  char(4),
     @vchObjectName nvarchar(255),
     @vchComment    nvarchar(255)='',
     @vchLoginName  nvarchar(255),
     @vchPassword   nvarchar(255)='',
     @iVCSFlags     int = 0,
     @iActionFlag   int = 0,   
     @txStream1     text = '',  
     @txStream2     text = '',  
     @txStream3     text = ''    as
set nocount on
	exec dbo.dt_checkinobject
		@chObjectType,
		@vchObjectName,
		@vchComment,
		@vchLoginName,
		@vchPassword,
		@iVCSFlags,
		@iActionFlag,   
		@txStream1,		
		@txStream2,		
		@txStream3
go


create procedure dbo.dt_checkoutobject @chObjectType  char(4),
     @vchObjectName varchar(255),
     @vchComment    varchar(255),
     @vchLoginName  varchar(255),
     @vchPassword   varchar(255),
     @iVCSFlags     int = 0,
     @iActionFlag   int = 0 as
set nocount on

	declare @iReturn int
	declare @iObjectId int
	select @iObjectId =0

	declare @VSSGUID varchar(100)
	select @VSSGUID = 'SQLVersionControl.VCS_SQL'

	declare @iReturnValue int
	select @iReturnValue = 0

	declare @vchTempText varchar(255)

	
	declare @iStreamObjectId int
	select @iStreamObjectId = 0

    declare @iPropertyObjectId int
    select @iPropertyObjectId = (select objectid from dbo.dtproperties where property = 'VCSProjectID')

    declare @vchProjectName   varchar(255)
    declare @vchSourceSafeINI varchar(255)
    declare @vchServerName    varchar(255)
    declare @vchDatabaseName  varchar(255)
    exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSProject',       @vchProjectName   OUT
    exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSourceSafeINI', @vchSourceSafeINI OUT
    exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSQLServer',     @vchServerName    OUT
    exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSQLDatabase',   @vchDatabaseName  OUT

    if @chObjectType = 'PROC'
    begin
        

        exec @iReturn = master.dbo.sp_OACreate @VSSGUID, @iObjectId OUT

        if @iReturn <> 0 GOTO E_OAError

        exec @iReturn = master.dbo.sp_OAMethod @iObjectId,
												'CheckOut_StoredProcedure',
												NULL,
												@sProjectName = @vchProjectName,
												@sSourceSafeINI = @vchSourceSafeINI,
												@sObjectName = @vchObjectName,
												@sServerName = @vchServerName,
												@sDatabaseName = @vchDatabaseName,
												@sComment = @vchComment,
												@sLoginName = @vchLoginName,
												@sPassword = @vchPassword,
												@iVCSFlags = @iVCSFlags,
												@iActionFlag = @iActionFlag

        if @iReturn <> 0 GOTO E_OAError


        exec @iReturn = master.dbo.sp_OAGetProperty @iObjectId, 'GetStreamObject', @iStreamObjectId OUT

        if @iReturn <> 0 GOTO E_OAError

        create table #commenttext (id int identity, sourcecode varchar(255))


        select @vchTempText = 'STUB'
        while @vchTempText is not null
        begin
            exec @iReturn = master.dbo.sp_OAMethod @iStreamObjectId, 'GetStream', @iReturnValue OUT, @vchTempText OUT
            if @iReturn <> 0 GOTO E_OAError
            
            if (@vchTempText = '') set @vchTempText = null
            if (@vchTempText is not null) insert into #commenttext (sourcecode) select @vchTempText
        end

        select 'VCS'=sourcecode from #commenttext order by id
        select 'SQL'=text from syscomments where id = object_id(@vchObjectName) order by colid

    end

CleanUp:
    return

E_OAError:
    exec dbo.dt_displayoaerror @iObjectId, @iReturn
    GOTO CleanUp
go


create procedure dbo.dt_checkoutobject_u @chObjectType  char(4),
     @vchObjectName nvarchar(255),
     @vchComment    nvarchar(255),
     @vchLoginName  nvarchar(255),
     @vchPassword   nvarchar(255),
     @iVCSFlags     int = 0,
     @iActionFlag   int = 0 as
set nocount on
	exec dbo.dt_checkoutobject
		@chObjectType,  
		@vchObjectName, 
		@vchComment,    
		@vchLoginName,  
		@vchPassword,  
		@iVCSFlags,    
		@iActionFlag
go


create procedure dbo.dt_displayoaerror_u @iObject int,
     @iresult int as
set nocount on
	exec dbo.dt_displayoaerror
		@iObject,
		@iresult
go


create procedure dbo.dt_droppropertiesbyid @id int,
 	@property varchar(64) as
set nocount on

	if (@property is null) or (@property = '')
		delete from dbo.dtproperties where objectid=@id
	else
		delete from dbo.dtproperties 
			where objectid=@id and property=@property
go


create procedure dbo.dt_dropuserobjectbyid @id int as
set nocount on
	delete from dbo.dtproperties where objectid=@id
go


create procedure dbo.dt_generateansiname (@name varchar(255) output) as
declare @prologue varchar(20) 
	declare @indexstring varchar(20) 
	declare @index integer 
 
	set @prologue = 'MSDT-A-' 
	set @index = 1 
 
	while 1 = 1 
	begin 
		set @indexstring = cast(@index as varchar(20)) 
		set @name = @prologue + @indexstring 
		if not exists (select value from dtproperties where value = @name) 
			break 
		 
		set @index = @index + 1 
 
		if (@index = 10000) 
			goto TooMany 
	end 
 
Leave: 
 
	return 
 
TooMany: 
 
	set @name = 'DIAGRAM' 
	goto Leave
go


create procedure dbo.dt_getobjwithprop @property varchar(30),
 	@value varchar(255) as
set nocount on

	if (@property is null) or (@property = '')
	begin
		raiserror('Must specify a property name.',-1,-1)
		return (1)
	end

	if (@value is null)
		select objectid id from dbo.dtproperties
			where property=@property

	else
		select objectid id from dbo.dtproperties
			where property=@property and value=@value
go


create procedure dbo.dt_getobjwithprop_u @property varchar(30),
 	@uvalue nvarchar(255) as
set nocount on

	if (@property is null) or (@property = '')
	begin
		raiserror('Must specify a property name.',-1,-1)
		return (1)
	end

	if (@uvalue is null)
		select objectid id from dbo.dtproperties
			where property=@property

	else
		select objectid id from dbo.dtproperties
			where property=@property and uvalue=@uvalue
go


create procedure dbo.dt_getpropertiesbyid @id int,
 	@property varchar(64) as
set nocount on

	if (@property is null) or (@property = '')
		select property, version, value, lvalue
			from dbo.dtproperties
			where  @id=objectid
	else
		select property, version, value, lvalue
			from dbo.dtproperties
			where  @id=objectid and @property=property
go


create procedure dbo.dt_getpropertiesbyid_u @id int,
 	@property varchar(64) as
set nocount on

	if (@property is null) or (@property = '')
		select property, version, uvalue, lvalue
			from dbo.dtproperties
			where  @id=objectid
	else
		select property, version, uvalue, lvalue
			from dbo.dtproperties
			where  @id=objectid and @property=property
go


create procedure dbo.dt_getpropertiesbyid_vcs_u @id       int,
     @property varchar(64),
     @value    nvarchar(255) = NULL OUT as
set nocount on
    exec dbo.dt_getpropertiesbyid_vcs
		@id,
		@property,
		@value output
go


create procedure dbo.dt_isundersourcecontrol @vchLoginName varchar(255) = '',
     @vchPassword  varchar(255) = '',
     @iWhoToo      int = 0  as
set nocount on

	declare @iReturn int
	declare @iObjectId int
	select @iObjectId = 0

	declare @VSSGUID varchar(100)
	select @VSSGUID = 'SQLVersionControl.VCS_SQL'

	declare @iReturnValue int
	select @iReturnValue = 0

	declare @iStreamObjectId int
	select @iStreamObjectId   = 0

	declare @vchTempText varchar(255)

    declare @iPropertyObjectId int
    select @iPropertyObjectId = (select objectid from dbo.dtproperties where property = 'VCSProjectID')

    declare @vchProjectName   varchar(255)
    declare @vchSourceSafeINI varchar(255)
    declare @vchServerName    varchar(255)
    declare @vchDatabaseName  varchar(255)
    exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSProject',       @vchProjectName   OUT
    exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSourceSafeINI', @vchSourceSafeINI OUT
    exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSQLServer',     @vchServerName    OUT
    exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSQLDatabase',   @vchDatabaseName  OUT

    if (@vchProjectName = '')	set @vchProjectName		= null
    if (@vchSourceSafeINI = '') set @vchSourceSafeINI	= null
    if (@vchServerName = '')	set @vchServerName		= null
    if (@vchDatabaseName = '')	set @vchDatabaseName	= null
    
    if (@vchProjectName is null) or (@vchSourceSafeINI is null) or (@vchServerName is null) or (@vchDatabaseName is null)
    begin
        RAISERROR('Not Under Source Control',16,-1)
        return
    end

    if @iWhoToo = 1
    begin

        
        exec @iReturn = master.dbo.sp_OACreate @VSSGUID, @iObjectId OUT
        if @iReturn <> 0 GOTO E_OAError

        exec @iReturn = master.dbo.sp_OAMethod @iObjectId,
												'GetListOfObjects',
												NULL,
												@vchProjectName,
												@vchSourceSafeINI,
												@vchServerName,
												@vchDatabaseName,
												@vchLoginName,
												@vchPassword

        if @iReturn <> 0 GOTO E_OAError

        exec @iReturn = master.dbo.sp_OAGetProperty @iObjectId, 'GetStreamObject', @iStreamObjectId OUT

        if @iReturn <> 0 GOTO E_OAError

        create table #ObjectList (id int identity, vchObjectlist varchar(255))

        select @vchTempText = 'STUB'
        while @vchTempText is not null
        begin
            exec @iReturn = master.dbo.sp_OAMethod @iStreamObjectId, 'GetStream', @iReturnValue OUT, @vchTempText OUT
            if @iReturn <> 0 GOTO E_OAError
            
            if (@vchTempText = '') set @vchTempText = null
            if (@vchTempText is not null) insert into #ObjectList (vchObjectlist ) select @vchTempText
        end

        select vchObjectlist from #ObjectList order by id
    end

CleanUp:
    return

E_OAError:
    exec dbo.dt_displayoaerror @iObjectId, @iReturn
    goto CleanUp
go


create procedure dbo.dt_isundersourcecontrol_u @vchLoginName nvarchar(255) = '',
     @vchPassword  nvarchar(255) = '',
     @iWhoToo      int = 0  as
set nocount on
	exec dbo.dt_isundersourcecontrol
		@vchLoginName,
		@vchPassword,
		@iWhoToo
go


create procedure dbo.dt_removefromsourcecontrol as
set nocount on

    declare @iPropertyObjectId int
    select @iPropertyObjectId = (select objectid from dbo.dtproperties where property = 'VCSProjectID')

    exec dbo.dt_droppropertiesbyid @iPropertyObjectId, null

    
    if @@error <> 0 and @@error <> -1 return 1

    return 0
go


create procedure dbo.dt_setpropertybyid_u @id int,
 	@property varchar(64),
 	@uvalue nvarchar(255),
 	@lvalue image as
set nocount on
	
	
	
	
	declare @avalue varchar(255) 
	set @avalue = null 
	if (@uvalue is not null) 
	begin 
		if (convert(nvarchar(255), convert(varchar(255), @uvalue)) = @uvalue) 
		begin 
			set @avalue = convert(varchar(255), @uvalue) 
		end 
		else 
		begin 
			if 'DtgSchemaNAME' = @property 
			begin 
				exec dbo.dt_generateansiname @avalue output 
			end 
		end 
	end 
	if exists (select * from dbo.dtproperties 
			where objectid=@id and property=@property)
	begin
		--
		
		--
		update dbo.dtproperties set value=@avalue, uvalue=@uvalue, lvalue=@lvalue, version=version+1
			where objectid=@id and property=@property
	end
	else
	begin
		--
		
		--
		insert dbo.dtproperties (property, objectid, value, uvalue, lvalue)
			values (@property, @id, @avalue, @uvalue, @lvalue)
	end
go


create procedure dbo.dt_validateloginparams @vchLoginName  varchar(255),
     @vchPassword   varchar(255) as
set nocount on

declare @iReturn int
declare @iObjectId int
select @iObjectId =0

declare @VSSGUID varchar(100)
select @VSSGUID = 'SQLVersionControl.VCS_SQL'

    declare @iPropertyObjectId int
    select @iPropertyObjectId = (select objectid from dbo.dtproperties where property = 'VCSProjectID')

    declare @vchSourceSafeINI varchar(255)
    exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSourceSafeINI', @vchSourceSafeINI OUT

    exec @iReturn = master.dbo.sp_OACreate @VSSGUID, @iObjectId OUT
    if @iReturn <> 0 GOTO E_OAError

    exec @iReturn = master.dbo.sp_OAMethod @iObjectId,
											'ValidateLoginParams',
											NULL,
											@sSourceSafeINI = @vchSourceSafeINI,
											@sLoginName = @vchLoginName,
											@sPassword = @vchPassword
    if @iReturn <> 0 GOTO E_OAError

CleanUp:
    return

E_OAError:
    exec dbo.dt_displayoaerror @iObjectId, @iReturn
    GOTO CleanUp
go


create procedure dbo.dt_validateloginparams_u @vchLoginName  nvarchar(255),
     @vchPassword   nvarchar(255) as
set nocount on
	exec dbo.dt_validateloginparams
		@vchLoginName,
		@vchPassword
go


create procedure dbo.dt_vcsenabled as
set nocount on

declare @iObjectId int
select @iObjectId = 0

declare @VSSGUID varchar(100)
select @VSSGUID = 'SQLVersionControl.VCS_SQL'

    declare @iReturn int
    exec @iReturn = master.dbo.sp_OACreate @VSSGUID, @iObjectId OUT
    if @iReturn <> 0 raiserror('', 16, -1) 
go


create procedure dbo.dt_verstamp006 as
select 7000
go


create procedure dbo.dt_verstamp007 as
select 7005
go


create procedure dbo.dt_whocheckedout @chObjectType  char(4),
         @vchObjectName varchar(255),
         @vchLoginName  varchar(255),
         @vchPassword   varchar(255) as
set nocount on

declare @iReturn int
declare @iObjectId int
select @iObjectId =0

declare @VSSGUID varchar(100)
select @VSSGUID = 'SQLVersionControl.VCS_SQL'

    declare @iPropertyObjectId int

    select @iPropertyObjectId = (select objectid from dbo.dtproperties where property = 'VCSProjectID')

    declare @vchProjectName   varchar(255)
    declare @vchSourceSafeINI varchar(255)
    declare @vchServerName    varchar(255)
    declare @vchDatabaseName  varchar(255)
    exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSProject',       @vchProjectName   OUT
    exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSourceSafeINI', @vchSourceSafeINI OUT
    exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSQLServer',     @vchServerName    OUT
    exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSQLDatabase',   @vchDatabaseName  OUT

    if @chObjectType = 'PROC'
    begin
        exec @iReturn = master.dbo.sp_OACreate @VSSGUID, @iObjectId OUT

        if @iReturn <> 0 GOTO E_OAError

        declare @vchReturnValue varchar(255)
        select @vchReturnValue = ''

        exec @iReturn = master.dbo.sp_OAMethod @iObjectId,
												'WhoCheckedOut',
												@vchReturnValue OUT,
												@sProjectName = @vchProjectName,
												@sSourceSafeINI = @vchSourceSafeINI,
												@sObjectName = @vchObjectName,
												@sServerName = @vchServerName,
												@sDatabaseName = @vchDatabaseName,
												@sLoginName = @vchLoginName,
												@sPassword = @vchPassword

        if @iReturn <> 0 GOTO E_OAError

        select @vchReturnValue

    end

CleanUp:
    return

E_OAError:
    exec dbo.dt_displayoaerror @iObjectId, @iReturn
    GOTO CleanUp
go


create procedure dbo.dt_whocheckedout_u @chObjectType  char(4),
         @vchObjectName nvarchar(255),
         @vchLoginName  nvarchar(255),
         @vchPassword   nvarchar(255) as
set nocount on
	exec dbo.dt_whocheckedout
		@chObjectType, 
		@vchObjectName,
		@vchLoginName, 
		@vchPassword
go


create procedure dbo.fit_card_resvlog_add @Verifycode nvarchar(50),
 @CardNO nvarchar(100),
 @Confnum nvarchar(50),
 @Remark nvarchar(500),
 @MemberType nvarchar(100),
 @UserID int,
 @Corp_ID int,
 @fit_userid uniqueidentifier='00000000-0000-0000-0000-000000000000' as
insert into fit_card_resvlog(Verifycode,CardNO,Confnum,Remark,MemberType,UserID,Corp_ID,fit_userid)
values(@Verifycode,@CardNO,@Confnum,@Remark,@MemberType,@UserID,@Corp_ID,@fit_userid)
go


create procedure dbo.getArticle @PageIndex int,
 @Pagesize int as
declare @sql varchar(500)
   declare @curpagenum int
   declare @nextpagenum int
   set @curpagenum=@PageIndex*@Pagesize
   set @nextpagenum=(@PageIndex)*@Pagesize
   begin
         set @sql='select top '+cast(@Pagesize as varchar)+' a.classid, a.title,a.subtitle,a.updatetime,b.ClassName,ArticleID from Article as a left join ArticleClass as b  
on a.ClassID=b.ClassID  where a.ClassID=b.ClassID and ArticleID not in (select  top '+cast(@nextpagenum as varchar)+' ArticleID from Article order by articleid desc) order by articleid desc'
   end 
   exec(@sql)
   print @sql
go


create procedure dbo.getCustomLen @parentid varchar(50) as
declare @str varchar(4000)
declare @i int
set @str=(select customhotel from corp where corp_id=@parentid)
declare @v_SQL varchar(4200)
SET @v_SQL = 'select count(*) from hotel where hotel_id in(' + @str + '0)'

exec(@v_SQL)

go


create procedure dbo.get_ACFeedback @confnum nvarchar(50),@gusetname as
nvarchar(100),@hotelname as nvarchar(200),@scheckin as nvarchar(50),@echeckin as nvarchar(50),@scheckout as nvarchar(50),@echeckout as nvarchar(50),
@startdate as nvarchar(50),@enddate as nvarchar(50),
@pagesize as int,@PageIndex as int
as 
declare @s as nvarchar(1000);
declare @SQL as nvarchar(1000);
declare @exe as nvarchar(4000)
set @s=' where 1=1 ';
if(@confnum!='')
begin
set @s=@s+(' and confnum='+@confnum)
end
if(@gusetname!='')
begin
set @s=@s+(' and gusetname='+@gusetname)
end
if(@hotelname!='')
begin
set @s=@s+(' and  hotelname='+@hotelname)
end
if(@scheckin!='')
begin
if(@echeckin!='')
begin
set @s=@s+('and (checkin>='''+@scheckin+''' and checkin<='''+@echeckin+''')')
end
end
if(@scheckout!='')
begin
if(@scheckout!='')
begin
set @s=@s+(' and (checkout>='''+@scheckout+''' and checkout<='''+@echeckout+''')')
end
end
if(@startdate!='')
begin
if(@enddate!='')
begin
set @s=@s+(' and (fbdate>='''+@startdate+''' and fbdate<='''+@enddate+''')')
end
end
set @SQL='select a.* into #tempsort from ac_feedback as a'+@s;
print(@SQL)
exec(@SQL)


set @exe=@SQL
set @exe=@exe+';select @@rowcount;'
set @exe=@exe+'select * from #tempsort where [id] in (select [id] from (select top  '+str(@pagesize*@PageIndex)+' [id] from #tempsort   order by fbdate desc)a)and [id] not in (select [id] from (select top '+str(@pagesize*@PageIndex-@pagesize)+' [id] from #tempsort  order by fbdate desc)a) order by fbdate desc;'
set @exe=@exe+'drop table #tempsort';
exec(@exe);
go


create procedure dbo.get_AcCompay @iata nvarchar(50),@corpname as
nvarchar(200),@date as nvarchar(50),
@pagesize as int,@PageIndex as int
as 
declare @s as nvarchar(1000);
declare @SQL as nvarchar(1000);
declare @exe as nvarchar(4000)
set @s=' where 1=1 ';
if(@iata!='')
begin
set @s=@s+(' and a.iata='+@iata)
end


if(@date!='')
begin
set @s=@s+('and (a.updatetime>='''+@date+''' and a.updatetime<='''+@date+''')')
end

if(@corpname!='')
begin
set @s=@s+(' and a.iata in(select iata from corp where corp_name like ''%'+@corpname+'%'')')
end

set @SQL='select a.*,b.corp_name into #tempsort from ac_Compay a left join  corp b on a.iata=b.iata'+@s
print(@SQL)



set @exe=@SQL
set @exe=@exe+';select @@rowcount;'
set @exe=@exe+'select * from #tempsort where [id] in (select [id] from (select top  '+str(@pagesize*@PageIndex)+' [id] from #tempsort   order by updatetime desc)a)and [id] not in (select [id] from (select top '+str(@pagesize*@PageIndex-@pagesize)+' [id] from #tempsort  order by updatetime desc)a) order by updatetime desc;'
set @exe=@exe+'drop table #tempsort';
print(@exe)
exec(@exe);
go


create procedure dbo.getfit_engine_domain @userid int as
select webdomain,css,sloganResv,sloganMod,sloganCxl,sloganNewResv,EmailFrom,EmailAlias,EmailTitle from crm_fit_engine_domain
where userid=@userid
go


create procedure dbo.gethotelrateplan @property_id int,
 @days int,
 @ratecode nvarchar(500),
 @checkin nvarchar(50) as
declare @checkout nvarchar(50)
set @checkout=dateadd(day,@days,convert(datetime,@checkin))
declare @stemp varchar(6000)
set @stemp='select distinct a.plancode,
(case when convert(char(10),a.availdate,020) = ''1900-01-01'' then ''-'' when convert(char(10),a.availdate,020) is null then ''-'' else convert(char(10),a.availdate,020) end) as availdate,a.allotment,allotmax,a.avstat,a.Maxlos,a.MinLos,a.ratecode,a.roomcode,
a.gua,a.cxl,a.pricenotax,
b.roomname,b.plandesc,b.roomdesc,a.CurrencyCode,b.AddBed,b.Net,b.Nosmoke,a.BreakfastNum,a.BreakfastPay from h_cache as a left join h_plan as b  on (a.plancode=b.plancode and a.property_id=b.property_id) 
where(a.availdate<'''+@checkout+''' and a.availdate>='''+@checkin+'''and a.avstat!=''N'' and a.PriceNoTax>0 and  (( datediff(hh,getdate(),a.Availdate)+24>=a.cutoff )
and a.Property_id='+replace(str(@property_id),' ','')+' and b.languagetype=0))'
if(@ratecode!='')
begin
set @stemp=@stemp+' and '+@ratecode
end
set @stemp=@stemp+'   order by a.plancode,availdate'
exec( @stemp  )
go


create function dbo.hfg_addelement (@orgValue    varchar(8000),
  @median      int,
  @element     varchar(64))
RETURNS  varchar(64)    
AS 
 
 Begin
    
     declare @zero  varchar(64)
     declare @retVal varchar(64)
     declare @diffNum int 
    declare @i2 int 
    set @i2=1
     set @diffNum=@median-len(@orgValue)
     set @zero=''
     while @i2<=@diffNum
	begin   
           set @zero=@zero+@element
           set @i2=@i2+1
        end
      set @retVal=@zero+@orgValue
     return @retVal
 End
go


create procedure dbo.hfg_applypresentrollback @verifycode varchar(50) as
declare @error int 
 declare @uid int
 declare @result int 
 declare @prscount int



  update hfg_present set prscount=prscount+(select prscount from hfg_present_consume where hfg_present_consume.prsid=hfg_present.prsid and hfg_present_consume.verifycode=@verifycode)  where  prsid IN  (SELECT prsid  FROM hfg_present_consume    WHERE verifycode =@verifycode )
  select @error=@@Error


begin transaction
  delete from hfg_present_consume where verifycode=@verifycode
  select @error=@error+@@Error


  delete from hfg_scorelog where verifycode=@verifycode
  select @error=@error+@@Error


if @error<>0
  begin
   rollback tran
   set @result=0
   return
  end
else
  begin
   commit tran
   set @result=2
 end



update hfg_user set scores=(select sum(score)  from hfg_scorelog where uid=@uid and valid=1),scorefreeze=-(select sum(score)  from hfg_scorelog where uid=@uid and valid=1 and scorestatus=1)  where uid=@uid



select @result
go


create procedure dbo.hfg_applypresent @uid int, --
 @prsid int,
 @count int, 
 @verifycode varchar(50)='0' as
declare @scorecount decimal 
 declare @myscore decimal 
 declare @error int 
 declare @conid int 
 declare @prscount int 
 declare @prscode varchar(10)
 declare @result int 

select @scorecount=prsscore*@count,@prscount=prscount from hfg_present where prsid=@prsid
select @myscore=scores from hfg_user where uid=@uid


if @prscount<@count
begin
 set @result=-1
 return
end


if  @scorecount<@myscore
begin

begin transaction
 insert into hfg_present_consume(prsid,gid,pid,prsname,simg,bimg,prscomment,prsscore,uid,condate,precount,concount,enddate,prscode,prstype,status,verifycode,fogid) select prsid,gid,pid,prsname,simg,bimg,prscomment,prsscore,@uid,getdate(),@count,@scorecount,enddate,'0',prstype,0,@verifycode,'0'  from hfg_present where prsid=@prsid
select @error=@@Error

set @conid=scope_identity()
set @prscode=dbo.hfg_presentcode(@conid)
update hfg_present_consume set prscode=@prscode where conid=@conid
select @error=@error+@@Error


 insert into hfg_scorelog(uid,conid,scoredate,logsort,score,valid,hid,gid,scorestatus,verifycode,fogid) select @uid,conid,getdate(),7,-@scorecount,1,pid,gid,1,@verifycode,'0' from hfg_present_consume where conid=@conid
select @error=@error+@@Error


update hfg_present set prscount=prscount-@count where prsid=@prsid
select @error=@error+@@Error


if @error<>0
 begin
 rollback tran
 set @result=0
 exec hfg_applypresentrollback @verifycode
 end
else
 begin
 commit tran
 set @result=2
 
 update hfg_user set scores=(select sum(score)  from hfg_scorelog where uid=@uid and valid=1),scorefreeze=-(select sum(score)  from hfg_scorelog where uid=@uid and valid=1 and scorestatus=1)  where uid=@uid
 end

end
else
begin
  set @result=1
end

select @result
go


create procedure dbo.hfg_applypresentfogok @verifycode varchar(50),
 @fogid varchar(50) as
declare @error int 
 declare @result int 



update hfg_present_consume set fogid=@fogid where verifycode=@verifycode
select @error=@@Error


update hfg_scorelog set fogid=@fogid where verifycode=@verifycode
  select @error=@error+@@Error

if @error<>0
  begin
   rollback tran
   set @result=0
   return
  end
else
  begin
   commit tran
   set @result=2
 end

select @result
go


create procedure dbo.hfg_batchcardnumberinsert (
     @orgId      int,
     @orgType    tinyint,
     @cardType   int,
     @templateNo varchar(256),
     @startNum   int,
     @endNum     int,
     @median     int,
     @idOut      int  output
 ) as
if len(@endNum)>@median 
        begin
            set  @idOut=1
            return
        end
	    declare @cardnumber varchar(50)
        declare @i1 int
        set @i1=charindex('$',@templateNo)
        if  @i1>0 
              set @templateNo=substring(@templateNo,1,@i1-1)
        else
        begin
            set  @idOut=2
            return 
        end
        if @startNum>@endNum 
        begin
            set @idOut=3
            return
        end
        if sign(@startNum)=-1 or sign(@endNum)=-1
        begin
            set @idOut=4
            return
        end 
	while @startNum<=@endNum
	begin
		set @cardnumber=@templateNo+Dbo.hfg_addelement(@startNum,@median,'0')
		if not exists(select * from hfg_cardnumber where cardnumber=@cardnumber and orgid=@orgid and orgtype=@orgtype)
		   
		     insert into hfg_cardnumber(orgid,orgtype,cardnumber,cardtype) values(@orgId,@orgType,@cardnumber,@cardType)
	        set @startNum=@startNum+1
	end
go


create procedure dbo.hfg_buyscore @gid int,
 @uid int,
 @totalmoney decimal,
 @admin varchar(50),
 @result decimal output as
declare @error int
declare @scorerate decimal(18,4)
declare @totalscore decimal(18,4)

select @scorerate=scoreratebuy from hfg_org_domain where orgid=@gid and scorebuy=1
set @totalscore=@scorerate*@totalmoney

begin transaction
insert into hfg_scorebuylog(gid,uid,scorerate,totalmoney,totalscore,admin) values(@gid,@uid,@scorerate,@totalmoney,@totalscore,@admin)
select @error=@@Error

insert into hfg_scorelog(uid,logsort,score,gid) values(@uid,3,@totalscore,@gid)
select @error=@error+@@Error

if(@error<>0)
begin
  rollback tran
  set @result=0
end
else
begin
  commit tran
  set @result=@totalscore
end
go


create procedure dbo.hfg_cardnumberdistribute (
     @gid      int,
     @uid      int,
     @cardId   int,
     @useadm   varchar(50),
     @comment  varchar(200),  
     @idOut    int  output
 ) as
declare @cardnumber varchar(50)
     declare @cardtype   int
     declare @record1    int
     declare @error1     int
     select @cardtype=cardtype,@cardnumber=cardnumber from hfg_cardnumber where cardid=@cardId and (uid=0 or isnull(uid,'')='')
     select @record1=@@RowCount
     if @record1=0
     begin
        set @idOut=10
        return
     end 
     select * from hfg_user where uid=@uid and gid=@gid and (lvlid=0 or isnull(lvlid,'')='')
     select @record1=@@RowCount
     if @record1=0
     begin
        set @idOut=11
        return
     end
     
     select * from hfg_user_cardnumber where uid=@uid and gid=@gid 
     select @record1=@@RowCount
     if @record1>0
     begin
        set @idOut=12
        return
     end
     
    begin transaction
    update hfg_user set lvlid=@cardtype  from hfg_user where uid=@uid
    select @error1=@error1+@@Error
    
    update hfg_cardnumber set uid = @uid,useadm=@useadm,usedate=getdate(),comment=@comment from hfg_cardnumber where cardid=@cardId
    select @error1=@error1+@@Error
    
    insert hfg_user_cardnumber(cardnumber,gid,uid) values(@cardnumber,@gid,@uid)
    select @error1=@error1+@@Error
      
    if   @error1<>0   
    begin   
          rollback   tran   
    end   
    else   
    begin   
          commit   tran   
    end
go


create procedure dbo.hfg_getscorerate @uid int=0, 
 @gid int=0, 
 @cdate datetime, 
 @lvlid int=0 
if(@uid<>0) 
  select @lvlid=lvlid,@gid=gid from hfg_user where uid=@uid

if (@lvlid=0)
    select max(unitscore) as unitscore from  hfg_scoresetup where orgid=@gid and @cdate>startdate and @cdate<enddate
  else
    select max(unitscore) as unitscore from  hfg_scoresetup where orgid=@gid and lvlid like @lvlid and @cdate>startdate and @cdate<enddate
go


create procedure dbo.hfg_getuserscore @uid as
int
as
select sum(score) as score from hfg_scorelog where uid=@uid and valid=1
go


create procedure dbo.hfg_getuserscorefreeze @uid as
int
as
select sum(score) as score from hfg_scorelog where uid=@uid and valid=1 and scorestatus=0
go


create procedure dbo.hfg_hotelreport @days nvarchar(50),
     @types int,
     @gid nvarchar(50),
     @hid nvarchar(50) as
declare @searchday nvarchar(100)
declare @sqlstr nvarchar(2000)

BEGIN
 if(@types=1)
  set @searchday=' convert(char(7),hfg_bookview.indate,20) =convert(char(7),'''+@days+''',20) '
 else
  set @searchday=' convert(char(10),hfg_bookview.indate,20) =convert(char(10),'''+@days+''',20) '

if(@gid='0')
	set @sqlstr='select booktable.booktotal,booktable.bookid,booktable.booktitle,booktable.booknights,intable.intotal,intable.innights into #bookreport from (SELECT COUNT(*) AS booktotal, hfg_bookview.gid as bookid, hfg_group.grpname as booktitle,sum(hfg_bookview.room*hfg_bookview.nights) as booknights FROM hfg_bookview LEFT OUTER JOIN hfg_group ON hfg_group.gid = hfg_bookview.gid where '+@searchday+' GROUP BY hfg_bookview.gid, hfg_group.grpname) as booktable left outer join (SELECT COUNT(*) AS intotal,
 hfg_bookview.gid as bookid,sum(hfg_bookview.room*hfg_bookview.nights) as innights FROM hfg_bookview where '+@searchday+' and getstatus>6 GROUP BY hfg_bookview.gid) as intable on booktable.bookid=intable.bookid   order by booktable.booktotal desc'
else
 begin
  if(@hid='0')
    set @sqlstr='select booktable.booktotal,booktable.bookid,booktable.booktitle,booktable.booknights,intable.intotal,intable.innights into #bookreport from (SELECT COUNT(*) AS booktotal, hfg_bookview.hid as bookid, hfg_hotel.htlname as booktitle,sum(hfg_bookview.room*hfg_bookview.nights) as booknights FROM hfg_bookview LEFT OUTER JOIN hfg_hotel ON hfg_hotel.htlid = hfg_bookview.hid where '+@searchday+' and hfg_bookview.gid='+@gid+' GROUP BY hfg_bookview.hid, hfg_hotel.htlname) as booktable left outer
 join (SELECT COUNT(*) AS intotal, hfg_bookview.hid as bookid,sum(hfg_bookview.room*hfg_bookview.nights) as innights FROM hfg_bookview where '+@searchday+' and gid='+@gid+' and getstatus>6 GROUP BY hfg_bookview.hid) as intable on booktable.bookid=intable.bookid  order by booktable.booktotal desc'
  else
    set @sqlstr='select booktable.booktotal,booktable.bookid,booktable.booktitle,booktable.booknights,intable.intotal,intable.innights into #bookreport from (SELECT COUNT(*) AS booktotal, hfg_bookview.roomtype as bookid, hfg_bookview.roomtype as booktitle,sum(hfg_bookview.room*hfg_bookview.nights) as booknights FROM hfg_bookview where '+@searchday+' and hfg_bookview.hid='+@hid+' GROUP BY hfg_bookview.roomtype) as booktable left outer join (SELECT COUNT(*) AS intotal, hfg_bookview.roomtype as
 bookid,sum(hfg_bookview.room*hfg_bookview.nights) as innights FROM hfg_bookview where '+@searchday+' and hid='+@hid+' and getstatus>6 GROUP BY hfg_bookview.roomtype) as intable on booktable.bookid=intable.bookid order by booktable.booktotal desc'
 end

set @sqlstr=@sqlstr+';select * from #bookreport;select sum(booktotal) as booktotal,sum(intotal) as intotal,sum(booknights) as booknights,sum(innights) as innights from #bookreport'
exec(@sqlstr)
END
go


create procedure dbo.hfg_hotelreportall @days nvarchar(50),
     @types int,
     @gid nvarchar(50),
     @hid nvarchar(50) as
declare @searchday nvarchar(100)
declare @sqlstr nvarchar(2000)

BEGIN
 if(@types=1)
  set @searchday=' convert(char(7),hfg_resvlog.starttime,20) =convert(char(7),'''+@days+''',20) '
 else
  set @searchday=' convert(char(10),hfg_resvlog.starttime,20) =convert(char(10),'''+@days+''',20) '

if(@gid='0')
	set @sqlstr='select booktable.booktotal,booktable.bookid,booktable.booktitle,booktable.booknights,intable.intotal,intable.innights into #bookreport from (SELECT COUNT(*) AS booktotal, hfg_resvlog.groupid as bookid, hotelgroup.classname as booktitle,sum(hfg_resvlog.room*hfg_resvlog.nights) as booknights FROM hfg_resvlog LEFT OUTER JOIN hotelgroup ON hotelgroup.classid = hfg_resvlog.groupid where '+@searchday+' GROUP BY hfg_resvlog.groupid, hotelgroup.classname) as booktable left outer join (SELECT
 COUNT(*) AS intotal, hfg_resvlog.groupid as bookid,sum(hfg_resvlog.room*hfg_resvlog.nights) as innights FROM hfg_resvlog where '+@searchday+' and getstatus>6 GROUP BY hfg_resvlog.groupid) as intable on booktable.bookid=intable.bookid   order by booktable.booktotal desc'
else
 begin
  if(@hid='0')
    set @sqlstr='select booktable.booktotal,booktable.bookid,booktable.booktitle,booktable.booknights,intable.intotal,intable.innights into #bookreport from (SELECT COUNT(*) AS booktotal, hfg_resvlog.hotel_id as bookid, hotel.title as booktitle,sum(hfg_resvlog.room*hfg_resvlog.nights) as booknights FROM hfg_resvlog LEFT OUTER JOIN hotel ON hotel.hotel_id = hfg_resvlog.hotel_id where '+@searchday+' and hfg_resvlog.groupid='+@gid+' GROUP BY hfg_resvlog.hotel_id, hotel.title) as booktable left outer join
 (SELECT COUNT(*) AS intotal, hfg_resvlog.hotel_id as bookid,sum(hfg_resvlog.room*hfg_resvlog.nights) as innights FROM hfg_resvlog where '+@searchday+' and groupid='+@gid+' and getstatus>6 GROUP BY hfg_resvlog.hotel_id) as intable on booktable.bookid=intable.bookid  order by booktable.booktotal desc'
  else
    set @sqlstr='select booktable.booktotal,booktable.bookid,booktable.booktitle,booktable.booknights,intable.intotal,intable.innights into #bookreport from (SELECT COUNT(*) AS booktotal, hfg_resvlog.roomname as bookid, hfg_resvlog.roomname as booktitle,sum(hfg_resvlog.room*hfg_resvlog.nights) as booknights FROM hfg_resvlog where '+@searchday+' and hfg_resvlog.hotel_id='+@hid+' GROUP BY hfg_resvlog.roomname) as booktable left outer join (SELECT COUNT(*) AS intotal, hfg_resvlog.roomname as
 bookid,sum(hfg_resvlog.room*hfg_resvlog.nights) as innights FROM hfg_resvlog where '+@searchday+' and hotel_id='+@hid+' and getstatus>6 GROUP BY hfg_resvlog.roomname) as intable on booktable.bookid=intable.bookid order by booktable.booktotal desc'
 end

set @sqlstr=@sqlstr+';select * from #bookreport;select sum(booktotal) as booktotal,sum(intotal) as intotal,sum(booknights) as booknights,sum(innights) as innights from #bookreport'
exec(@sqlstr)
END
go


create procedure dbo.hfg_levelcount @lvlid int=0 
if (@lvlid=0) 
update hfg_levelsetup set lvlcount=(select count(*) from  hfg_user where hfg_user.lvlid=hfg_levelsetup.lvlid) 
else
update hfg_levelsetup set lvlcount=(select count(*) from  hfg_user where lvlid=@lvlid) where lvlid=@lvlid 
go


create procedure dbo.hfg_pagination @tblName varchar(255), 
 @strGetFields varchar(1000) = '*', 
 @fldName varchar(255)='', 
 @KeyName varchar(255)='',
 @PageSize int = 10, 
 @PageIndex int = 1, 
 @strWhere varchar(1500) = '' 
declare @strSQL varchar(5000) 
declare @strOrder varchar(400) 
begin 
   
begin 
set @strOrder = " order by " + @fldName 
       
end 
if @PageIndex = 1 
  begin 
        if @strWhere != '' 
           set @strSQL = "select top " + str(@PageSize) +" "+@strGetFields+ " from [" + @tblName + "] where " + @strWhere + " " + @strOrder 
        else 
           set @strSQL = "select top " + str(@PageSize) +" "+@strGetFields+ " from ["+ @tblName + "] "+ @strOrder 
           
  end 
else 
        begin 
        
        set @strSQL ="SELECT * FROM (SELECT TOP " + str(@PageSize) +" "+@strGetFields+ "  FROM " + @tblName + "  WHERE " + @KeyName + " NOT IN  ( SELECT TOP " + str(@PageSize*(@PageIndex-1)) +" " + @KeyName + "  FROM " + @tblName + " " + @strOrder + ") " + @strOrder + ")  tempa " 
        if @strWhere != '' 
        set @strSQL ="SELECT * FROM (SELECT TOP " + str(@PageSize) +" "+@strGetFields+ "  FROM " + @tblName + "  WHERE " + @KeyName + " NOT IN  ( SELECT TOP " + str(@PageSize*(@PageIndex-1)) +" " + @KeyName + "  FROM " + @tblName + " where  "+ @strWhere + " " + @strOrder + ")  and " + @strWhere + " " + @strOrder + ") tempa" 
        end 
end 
exec (@strSQL)
go


create procedure dbo.hfg_paginationc @tblName varchar(255), 
 @strGetFields varchar(1000) = '*', 
 @fldName varchar(255)='', 
 @KeyName varchar(255)='',
 @PageSize int = 10, 
 @PageIndex int = 1, 
 @strWhere varchar(1500) = '' 
declare @strSQL varchar(5000) 
declare @strOrder varchar(400) 
declare @strCount varchar(1000) 
begin 
   
begin 
set @strOrder = " order by " + @fldName 
       
end 
begin
if @strWhere!=''
set @strCount=";select count(*) as mm from "+@tblName +" where "+@strWhere
 else
set @strCount=";select count(*) as mm from "+@tblName 
end 
if @PageIndex = 1 
  begin 
        if @strWhere != '' 
           set @strSQL = "select top " + str(@PageSize) +" "+@strGetFields+ " from [" + @tblName + "] where " + @strWhere + " " + @strOrder 
        else 
           set @strSQL = "select top " + str(@PageSize) +" "+@strGetFields+ " from ["+ @tblName + "] "+ @strOrder 
           
  end 
else 
        begin 
        
        set @strSQL ="SELECT * FROM (SELECT TOP " + str(@PageSize) +" "+@strGetFields+ "  FROM " + @tblName + "  WHERE " + @KeyName + " NOT IN  ( SELECT TOP " + str(@PageSize*(@PageIndex-1)) +" " + @KeyName + "  FROM " + @tblName + " " + @strOrder + ") " + @strOrder + ")  tempa " 
        if @strWhere != '' 
        set @strSQL ="SELECT * FROM (SELECT TOP " + str(@PageSize) +" "+@strGetFields+ "  FROM " + @tblName + "  WHERE " + @KeyName + " NOT IN  ( SELECT TOP " + str(@PageSize*(@PageIndex-1)) +" " + @KeyName + "  FROM " + @tblName + " where  "+ @strWhere + " " + @strOrder + ")  and " + @strWhere + " " + @strOrder + ") tempa" 
        end 
end 
exec (@strSQL+@strCount)
go


create function dbo.hfg_presentcode (@orgValue    varchar(50))
RETURNS  varchar(64)    
AS 
 Begin
    
     declare @zero  varchar(64)
     declare @retVal varchar(64)
     declare @codelen int 
    declare @i2 int 
    
     set @i2=1
     set @codelen=10-len(@orgValue)
     set @zero='0'
     while @i2<@codelen
	begin   
           set @zero=@zero+'0'
           set @i2=@i2+1
        end
      set @retVal=@zero+@orgValue
     return @retVal
 End
go


create procedure dbo.hfg_report @daytype int,
 @reporttype nvarchar(50),
 @reportdate nvarchar(50),
 @search nvarchar(500) as
BEGIN
declare @sqlstr nvarchar(2000)

if( @daytype=1)
begin 
if(@reporttype='checkin')
set @sqlstr='SELECT  COUNT(*) AS counts, DATEPART(dd, indate) AS ditem  FROM         hfg_bookview WHERE '+@search+' and getstatus>5  and   (CONVERT(char(7), indate, 20) = '''+@reportdate+''') GROUP BY DATEPART(dd, indate)'
else if(@reporttype='noshow')
set @sqlstr='SELECT  COUNT(*) AS counts, DATEPART(dd, indate) AS ditem  FROM         hfg_bookview WHERE '+@search+' and   getstatus=5 and   (CONVERT(char(7), indate, 20) = '''+@reportdate+''') GROUP BY DATEPART(dd, indate)'
else
set @sqlstr='SELECT  COUNT(*) AS counts, DATEPART(dd, indate) AS ditem  FROM         hfg_bookview WHERE '+@search+' and    (CONVERT(char(7), indate, 20) = '''+@reportdate+''') GROUP BY DATEPART(dd, indate)'
end

else
begin 
if(@reporttype='checkin')
set @sqlstr='SELECT  COUNT(*) AS counts, DATEPART(mm, indate) AS ditem  FROM         hfg_bookview WHERE '+@search+' and   getstatus>5  and   (CONVERT(char(4), indate, 20) = '''+@reportdate+''') GROUP BY DATEPART(mm, indate)'
else if(@reporttype='noshow')
set @sqlstr='SELECT  COUNT(*) AS counts, DATEPART(mm, indate) AS ditem  FROM         hfg_bookview WHERE '+@search+' and   getstatus=5 and   (CONVERT(char(4), indate, 20) = '''+@reportdate+''') GROUP BY DATEPART(mm, indate)'
else
set @sqlstr='SELECT  COUNT(*) AS counts, DATEPART(mm, indate) AS ditem  FROM         hfg_bookview WHERE '+@search+' and    (CONVERT(char(4), indate, 20) = '''+@reportdate+''') GROUP BY DATEPART(mm, indate)'
end
exec(@sqlstr)
END
go


create procedure dbo.hfg_reportall @daytype int,
 @reporttype nvarchar(50),
 @reportdate nvarchar(50),
 @search nvarchar(500) as
BEGIN
declare @sqlstr nvarchar(2000)

if( @daytype=1)
begin 
if(@reporttype='checkin')
set @sqlstr='SELECT  COUNT(*) AS counts, DATEPART(dd, starttime) AS ditem  FROM         resvlog left join hotel on hotel.pid=resvlog.propertyid WHERE '+@search+' and getstatus>5  and   (CONVERT(char(7), starttime, 20) = '''+@reportdate+''') GROUP BY DATEPART(dd, starttime)'
else if(@reporttype='noshow')
set @sqlstr='SELECT  COUNT(*) AS counts, DATEPART(dd, starttime) AS ditem  FROM         resvlog left join hotel on hotel.pid=resvlog.propertyid WHERE '+@search+' and   getstatus=5 and   (CONVERT(char(7), starttime, 20) = '''+@reportdate+''') GROUP BY DATEPART(dd, starttime)'
else
set @sqlstr='SELECT  COUNT(*) AS counts, DATEPART(dd, starttime) AS ditem  FROM         resvlog left join hotel on hotel.pid=resvlog.propertyid WHERE '+@search+' and    (CONVERT(char(7), starttime, 20) = '''+@reportdate+''') GROUP BY DATEPART(dd, starttime)'
end

else
begin 
if(@reporttype='checkin')
set @sqlstr='SELECT  COUNT(*) AS counts, DATEPART(mm, starttime) AS ditem  FROM         resvlog left join hotel on hotel.pid=resvlog.propertyid WHERE '+@search+' and   getstatus>5  and   (CONVERT(char(4),starttime, 20) = '''+@reportdate+''') GROUP BY DATEPART(mm, starttime)'
else if(@reporttype='noshow')
set @sqlstr='SELECT  COUNT(*) AS counts, DATEPART(mm, starttime) AS ditem  FROM         resvlog left join hotel on hotel.pid=resvlog.propertyid WHERE '+@search+' and   getstatus=5 and   (CONVERT(char(4), starttime, 20) = '''+@reportdate+''') GROUP BY DATEPART(mm, starttime)'
else
set @sqlstr='SELECT  COUNT(*) AS counts, DATEPART(mm, starttime) AS ditem  FROM         resvlog left join hotel on hotel.pid=resvlog.propertyid WHERE '+@search+' and    (CONVERT(char(4), starttime, 20) = '''+@reportdate+''') GROUP BY DATEPART(mm, starttime)'
end
exec(@sqlstr)
END
go


create procedure dbo.hfg_updateuserscore @uid  int,
 @type int as
if @type=1
    begin
     update hfg_user set scores=(select sum(score)  from hfg_scorelog where uid=@uid and valid=1) where uid=@uid
    end
else
    begin
     if @type=2
     begin 
      update hfg_user set scorefreeze=-(select sum(score)  from hfg_scorelog where uid=@uid and valid=1 and scorestatus=1) where uid=@uid
     end 
     else
     begin
     update hfg_user set scores=(select sum(score)  from hfg_scorelog where uid=@uid and valid=1),scorefreeze=-(select sum(score)  from hfg_scorelog where uid=@uid and valid=1 and scorestatus=1)  where uid=@uid
     end
    
   end
go


create procedure dbo.hfg_userscorestat @uid int,
 @cyear int=0 as
declare @booktime int 
declare @strwhere varchar(100)  
declare @bookneight int  
declare @consumeneight int 
declare @consumehotel int 
declare @totalmount decimal 
declare @totalscore decimal 
declare @totalhotel int 

declare @lastday int

set @lastday=datediff(dd,'2008-1-1',getdate())  

if @cyear=0
  begin
   set  @cyear=convert(char(4),getdate(),20)
  end


select @booktime=count(*)  from hfg_scorelog where uid=@uid and logsort=1 and convert(char(4),logdate,20)=@cyear and valid=1 

if @booktime>0
begin
  
 select @bookneight=sum(datediff(dd,indate,outdate)) from hfg_scorelog where uid=@uid  and logsort=1 and convert(char(4),logdate,20)=@cyear and valid=1          
 select @consumeneight=sum(datediff(dd,indate,toutdate)),@totalmount=sum(consumetotal),@totalscore=sum(score),@totalhotel=count(distinct(hid)) from hfg_scorelog where uid=@uid  and logsort=1 and convert(char(4),toutdate,20)=@cyear and valid=1  
 
 if exists(select * from   hfg_user_score where uid=@uid and talyear=@cyear)
   update hfg_user_score set talbooktimes=@booktime,talroomnights=@bookneight,talconsumenights=@consumeneight,talmount=@totalmount,talscore=@totalscore,talhotelcount=@totalhotel,lastday=@lastday where uid=@uid and talyear=@cyear
 else
  insert into hfg_user_score(uid,talyear,talbooktimes,talroomnights,talconsumenights,talmount,talscore,lastday,talhotelcount) values(@uid,@cyear,@booktime,@bookneight,@consumeneight,@totalmount,@totalscore,@lastday,@totalhotel)
end

update hfg_user set bookingcount=(select sum(talbooktimes) from hfg_user_score where hfg_user_score.uid=@uid),nightcount=(select sum(talroomnights) from hfg_user_score where hfg_user_score.uid=@uid) where uid=@uid 
go


create procedure dbo.hfg_userupgrade @logid int,
 @gid int as
declare @uid int --
declare @lvlid int  --
declare @lastyear int 

set @lastyear=datepart(yyyy,getdate())+1 

if exists(select * from hfg_userup_templog where logid=@logid and gid=@gid)
begin
 select @uid=uid,@lvlid=lvlid from hfg_userup_templog where logid=@logid and gid=@gid
 update hfg_user set lvlid=@lvlid,endyear=@lastyear where uid=@uid
 select * from hfg_user where uid=@uid
 delete from hfg_userup_templog where logid=@logid
end
go


create procedure dbo.hotel_search @pid  int as
select * from hotel where pid=@pid
go


create procedure dbo.pro_GetHotelList @Title nvarchar(50),
 @City int,
 @District int,
 @Commercial int,
 @CheckIn datetime,
 @CheckOut datetime,
 @PriceRange nvarchar(50),
 @AirPortDistance int,
 @Stars int,
 @hotelGeography nvarchar(2000),
 @AirPortCode nvarchar(50),
 @ConfirmationType nvarchar(50),
 @Plan nvarchar(500), 
 @GroupID nvarchar(2000), 
 @PageSize int=10, 
 @CurPage int=1, 
 @doCount int 
declare @MyTitle nvarchar(50)
    
    set @Title=replace(@Title,'''','''''') 
    set @Title=replace(@Title,'--','') 
    set @Title=replace(@Title,';','') 
set @MyTitle = '%'+@Title+'%'
declare @Sql nvarchar(4000)
declare @sqlCount nvarchar(4000)
set @Sql='select  c.*,d.planname,d.roomname,d.plandesc,d.roomdesc into  #tempsort from (select a.hotel_id,a.pid,a.SpecialID,a.Title_e,a.title,a.pid_e,a.GroupID,a.ClassID,a.stars,a.Diamond,b.plancode,b.ratecode,b.roomcode,b.availdate,b.allotment,b.allotmax,b.avstat,b.maxlos,b.minlos,b.gua,b.cxl,b.pricenotax, a.credit,a.pagerank   from hotel as a left join h_cache as b '
set @Sql=@Sql+' on a.pid=b.property_id where a.passed=1 '


if(@GroupID!='')
begin
set @Sql=@Sql+@GroupID
end


if(@Title!='')
set @Sql=@Sql+' and (a.Title like '''+@MyTitle+''' or a.Title_e like '''+@MyTitle+''' or a.keywords like  ''%'+@MyTitle+'%'' )'

if (@Stars!=10)
	begin
		if(@Stars=0)
			set @Sql=@Sql+' and (a.Stars =0 and a.Diamond=0)'
		else
			set @Sql=@Sql+' and ((a.Stars ='+ cast(@Stars as varchar)+' and a.Diamond=0)  or (a.Diamond='+ cast(@Stars as varchar)+' and a.Stars=0))'
	end


if (@hotelGeography!='')
set @Sql=@Sql+' and a.address1 like''%'+@hotelGeography+'%'''

if (@City!=-1)
set @Sql=@Sql+' and a.cityid='+ cast(@City as varchar)

if (@District!=-1)
set @Sql=@Sql+' and a.districtid='+ cast(@District as varchar)

if (@Commercial!=-1)
set @Sql=@Sql+' and a.commercialid='+ cast(@Commercial as varchar)


if (@Plan!='')
	begin
	set @Sql=@Sql+' and '+@Plan --'  and  (ratecode=''JJADV5''  or  ratecode  = ''BARB'' or  ratecode  = ''BAR'')'
	end
if (@PriceRange!='')
begin
	declare @MyPriceRange nvarchar(100)
        
	if (@PriceRange='<=250')
	set @MyPriceRange ='priceNoTax>0 and priceNoTax<= 250'
	if (@PriceRange='250-400')
	set @MyPriceRange ='priceNoTax>250 and priceNoTax<=400'
	if (@PriceRange='400-600')
	set @MyPriceRange ='priceNoTax>400 and priceNoTax<=600'
	if (@PriceRange='600-800')
	set @MyPriceRange ='priceNoTax>600 and priceNoTax<=800'
	if (@PriceRange='>800')
	set @MyPriceRange ='priceNoTax> 800'

	set @Sql=@Sql+' and ('+@MyPriceRange+') '
	
end
else
begin
set @Sql =@Sql+ '  and  priceNoTax>0 '
end

set @Sql=@Sql+'  and avstat!=''N''  and (datediff(hh,getdate(),Availdate)+24>=cutoff)  and  Availdate>= '''+convert(varchar(10),@CheckIn,120)+''' AND Availdate<'''+convert(varchar(10),@CheckOut,120)+''''

set @Sql=@Sql+') as c '
set @Sql=@Sql+' left join h_plan as d  on c.pid=d.property_id where d.languagetype=0 and c.plancode=d.plancode'
set @Sql=@Sql+' order by  c.credit desc,c.pagerank desc,c.hotel_id,c.plancode,c.availdate asc,c.pricenotax asc;'
if(@CurPage=1)
begin
     set @Sql=@Sql+'  select * from #tempsort where pid in (select top 10 pid from (select  top '+str(@pagesize*@CurPage)+' *  
from(select pid,credit,pagerank from  #tempsort group by pid,credit,pagerank) a  order by   credit desc,pagerank desc) as e ) order by credit    desc,pagerank desc ;'
end
else
begin
     set @Sql=@Sql+'  select * from #tempsort where pid  in (select top 10 pid from (select top '+str(@pagesize*@CurPage)+' *
 from (select pid,credit,pagerank from  #tempsort group by pid,credit,pagerank) a  order by   credit desc,pagerank desc) as e order by pagerank asc,credit asc);'
end
set @Sql=@Sql+' select distinct pid from #tempsort;'
set @Sql=@Sql+'drop table #tempsort;'
print(@Sql)
exec (@Sql)
go


create procedure dbo.pro_GetHotelList2 @Title nvarchar(50),
 @City int,
 @District int,
 @Commercial int,
 @CheckIn datetime,
 @CheckOut datetime,
 @PriceRange nvarchar(50),
 @AirPortDistance int,
 @Stars int,
 @hotelGeography nvarchar(2000),
 @AirPortCode nvarchar(50),
 @ConfirmationType nvarchar(50),
 @Plan nvarchar(500), 
 @GroupID nvarchar(2000), 
 @PageSize int=10, 
 @CurPage int=1, 
 @doCount int 
declare @MyTitle nvarchar(50)
    
    set @Title=replace(@Title,'''','''''') 
    set @Title=replace(@Title,'--','') 
    set @Title=replace(@Title,';','') 
set @MyTitle = '%'+@Title+'%'
declare @Sql nvarchar(4000)
declare @sqlCount nvarchar(4000)
set @Sql='select  c.*,d.planname,d.roomname,d.plandesc,d.roomdesc into  #tempsort from (select a.hotel_id,a.pid,a.SpecialID,a.Title_e,a.title,a.pid_e,a.GroupID,a.ClassID,a.stars,a.Diamond,b.plancode,b.ratecode,b.roomcode,b.availdate,b.allotment,b.allotmax,b.avstat,b.maxlos,b.minlos,b.gua,b.cxl,b.pricenotax, a.credit,a.pagerank   from hotel as a left join h_cache as b '
set @Sql=@Sql+' on a.pid=b.property_id where a.passed=1 '


if(@GroupID!='')
begin
set @Sql=@Sql+@GroupID
end


if(@Title!='')
set @Sql=@Sql+' and (a.Title like '''+@MyTitle+''' or a.Title_e like '''+@MyTitle+''' or a.keywords like  ''%'+@MyTitle+'%'' )'

if (@Stars!=10)
	begin
		if(@Stars=0)
			set @Sql=@Sql+' and (a.Stars =0 and a.Diamond=0)'
		else
			set @Sql=@Sql+' and ((a.Stars ='+ cast(@Stars as varchar)+' and a.Diamond=0)  or (a.Diamond='+ cast(@Stars as varchar)+' and a.Stars=0))'
	end


if (@hotelGeography!='')
set @Sql=@Sql+' and a.address1 like''%'+@hotelGeography+'%'''

if (@City!=-1)
set @Sql=@Sql+' and a.cityid='+ cast(@City as varchar)

if (@District!=-1)
set @Sql=@Sql+' and a.districtid='+ cast(@District as varchar)

if (@Commercial!=-1)
set @Sql=@Sql+' and a.commercialid='+ cast(@Commercial as varchar)


if (@Plan!='')
	begin
	set @Sql=@Sql+' and '+@Plan --'  and  (ratecode=''JJADV5''  or  ratecode  = ''BARB'' or  ratecode  = ''BAR'')'
	end
if (@PriceRange!='')
begin
	declare @MyPriceRange nvarchar(100)
        
	if (@PriceRange='<=250')
	set @MyPriceRange ='priceNoTax>0 and priceNoTax<= 250'
	if (@PriceRange='250-400')
	set @MyPriceRange ='priceNoTax>250 and priceNoTax<=400'
	if (@PriceRange='400-600')
	set @MyPriceRange ='priceNoTax>400 and priceNoTax<=600'
	if (@PriceRange='600-800')
	set @MyPriceRange ='priceNoTax>600 and priceNoTax<=800'
	if (@PriceRange='>800')
	set @MyPriceRange ='priceNoTax> 800'

	set @Sql=@Sql+' and ('+@MyPriceRange+') '
	
end
else
begin
set @Sql =@Sql+ '  and  priceNoTax>0 '
end

set @Sql=@Sql+'  and avstat!=''N''  and (datediff(hh,getdate(),Availdate)+24>=cutoff)  and  Availdate>= '''+convert(varchar(10),@CheckIn,120)+''' AND Availdate<'''+convert(varchar(10),@CheckOut,120)+''''

set @Sql=@Sql+') as c '
set @Sql=@Sql+' left join h_plan as d  on c.pid=d.property_id where d.languagetype=0 and c.plancode=d.plancode'
set @Sql=@Sql+' order by  c.credit desc,c.pagerank desc,c.hotel_id,c.plancode,c.availdate asc,c.pricenotax asc;'
if(@CurPage=1)
begin
     set @Sql=@Sql+'  select * from #tempsort where pid in (select top 10 pid from (select distinct top '+str(@pagesize*@CurPage)+' pid from(select top 10000 pid from  #tempsort order by  credit desc,pagerank desc,hotel_id,plancode,availdate asc,pricenotax asc) as c) as e);'
end
else
begin
     set @Sql=@Sql+'  select * from #tempsort where pid  in (select distinct top 10 pid from #tempsort where pid not in (select distinct top '+str(@pagesize*(@CurPage-1))+' pid from (select top 10000 pid from #tempsort order by  credit desc,pagerank desc,hotel_id,plancode,availdate asc,pricenotax asc) as c));'
end
set @Sql=@Sql+' select distinct pid from #tempsort;'
set @Sql=@Sql+'drop table #tempsort;'
print(@Sql)
exec (@Sql)
go


create procedure dbo.pro_In_Ac_feedback @confnum nvarchar(50),
 @iata varchar(50),
 @chVoucher nvarchar(2000),
 @fbdate nvarchar(50) as
declare @count int
set @count=(select count(*) from ac_feedback where confnum=@confnum and iata=@iata)
if(@count>0)
begin
update ac_feedback
set chVoucher=chVoucher+@chVoucher
where confnum=@confnum and iata=@iata
end
else
begin
insert ac_feedback(confnum,chVoucher,fbdate,iata)
values(@confnum,@chVoucher,@fbdate,@iata)
end
go


create procedure dbo.pro_Mod_Ac_feedback @confnum nvarchar(50),
 @iata varchar(50),
 @gusetname nvarchar(100),
 @hotelname nvarchar(200),
 @checkin nvarchar(50),
 @checkout nvarchar(50),
 @totalamount decimal,
 @totalrevenue decimal,
 @roomno nvarchar(50),
 @hotelnum nvarchar(50),
 @remark text,
 @fbname nvarchar(100),
 @fbphone nvarchar(100),
 @fbdate nvarchar(50) as
declare @count int
set @count=(select count(*) from ac_feedback where confnum=@confnum and iata=@iata)
if(@count>0)
begin
update ac_feedback
set gusetname=@gusetname,
    hotelname=@hotelname,
    checkin=@checkin,
    checkout=@checkout,
    totalamount=@totalamount,
    totalrevenue=@totalrevenue,
    roomno=@roomno,
    hotelnum=@hotelnum,
    remark=@remark,
    fbname=@fbname,
    fbphone=@fbphone,
    fbdate=@fbdate
where confnum=@confnum and iata=@iata
end
else
begin
insert ac_feedback(confnum,gusetname,hotelname,checkin,checkout,totalamount,totalrevenue,roomno,hotelnum,remark,fbname,fbphone,fbdate,iata)
values(@confnum,@gusetname,@hotelname,@checkin,@checkout,@totalamount,@totalrevenue,@roomno,@hotelnum,@remark,@fbname,@fbphone,@fbdate,@iata)
end
go


create procedure dbo.pro_UpdateLog @username nvarchar(100),
 @verifycode nvarchar(100),
 @typecode int,
 @typename nvarchar(200),
 @updatetime varchar(50),
 @userip varchar(50),
 @upcontent ntext as
insert into update_log(username,verifycode,typecode,typename,updatetime,userip,upcontent)
values(@username,@verifycode,@typecode,@typename,@updatetime,@userip,@upcontent)
go


create procedure dbo.pro_checkResult @confnum nvarchar(50),
 @iata varchar(50) as
select checkstate,checkresult,checkremark from ac_feedback
where confnum=@confnum and iata=@iata
go


create procedure dbo.pro_getScore @iata nvarchar(100),
 @StartDate1 datetime,
 @EndDate1 datetime,
 @StartDate2 datetime,
 @EndDate2 datetime as
select score  from ac_balOrder where iata=@iata and (updatetime>=@StartDate1 and updatetime<=@EndDate1)
select * from ac_resvlog where iata=@iata and deptime>=@StartDate2 and deptime<=@EndDate2
go


create procedure dbo.pro_getnoshow @username nvarchar(50),
 @userlevel varchar(50),
 @corp_id varchar(50) as
declare @sql nvarchar(3000)
set @sql='select count([id]) from resvlog where DateDiff(d,deptime,getdate())<=3  and getstatus=5 and '
if(@userlevel='999')
begin
set @sql=@sql+' iata =(select distinct iata from [corp] where corp_id='+@corp_id+')'
end
else
begin
set @sql=@sql+' userid in(select userid from [user] where username='''+@username+''')'
end
exec(@sql)
go


create procedure dbo.pro_insertAc_BalOrder @iata nvarchar(50),
 @order_name nvarchar(200),
 @updatetime nvarchar(50) as
insert into ac_balOrder(iata,order_name,updatetime) values(@iata,@order_name,@updatetime)
go


create procedure dbo.pro_insertBalOrder @iata nvarchar(100),
 @webname nvarchar(200),
 @fax nvarchar(100),
 @linkuser nvarchar(100),
 @total decimal,
 @integral int,
 @allowance int,
 @CLeavings int,
 @CanIntegral int,
 @commision int,
 @Comtal int,
 @Change int,
 @order_name nvarchar(200),
 @updatetime nvarchar(200) as
insert into ac_balOrder(iata,webname,fax,linkuser,total,integral,allowance,Cleavings,CanIntegral,commision,Comtal,Change,order_name,updatetime)
values(@iata,@webname,@fax,@linkuser,@total,@integral,@allowance,@CLeavings,@CanIntegral,@commision,@Comtal,@Change,@order_name,@updatetime)
go


create procedure dbo.pro_insertComPay @iata nvarchar(50),
 @fpstate int,
 @senddate nvarchar(50),
 @comstate int,
 @username nvarchar(100),
 @link nvarchar(200),
 @updatetime nvarchar(50) as
declare @sql nvarchar(200)
insert into ac_ComPay (iata,fpstate,senddate,comstate,username,link,updatetime)
values(@iata,@fpstate,@senddate,@comstate,@username,@link,@updatetime)
go


create procedure dbo.pro_insertR_OverTime @verifycode nvarchar(50),
 @username nvarchar(100),
 @iata nvarchar(100),
 @hotelname nvarchar(200) as
insert into R_Overtime(verifycode,username,iata,hotelname)
values(@verifycode,@username,@iata,@hotelname)
go


create procedure dbo.selectHotel (
 	@Hotel_ID int
 	) as
select * from hotel where Hotel_ID=@Hotel_ID
go


create procedure dbo.setFeedBack @userid nvarchar(50),
 @usertype nvarchar(50),
 @inIp varchar(50),
 @url nvarchar(200),
 @typecode varchar(50),
 @content nvarchar(2000),
 @title nvarchar(200),
 @confnum nvarchar(50),
 @fromemail nvarchar(200),
 @toemail nvarchar(200),
 @updatetime varchar(50),
 @langaugetype int as
insert into FeedBack(userid,usertype,inIp,url,typecode,content,title,confnum,fromemail,toemail,updatetime,languagetype) values(@userid,@usertype,@inIp,@url,@typecode,@content,@title,@confnum,@fromemail,@toemail,@updatetime,@langaugetype)
go


create procedure dbo.sp_GetHotelDetail_3 (
 	@i_Hotel_ID int,
 	@i_PID int = null,
 	@i_Lan int = 1 
 ) as
IF @i_PID IS NOT NULL
		BEGIN
			IF @i_Lan = 0

				SELECT hb.title, hb.Stars, h.photourl, h.lowprice, h.highprice, hb.pid, hb.country, hb.CheckIn, hb.CheckOut,
						hb.address1, hb.address2, hb.currency, hb.photourl, hb.phone, h.Diamond, hb.city, hb.state, h.subtitle, hb.holdtime, hb.fax, h.pid, hb.fop, hb.zip, h.groupid
				FROM [h_baseinfo] hb
				JOIN [Hotel] h ON h.Hotel_ID = hb.Hotel_ID
				WHERE hb.pid = @i_PID AND hb.languagetype = @i_Lan
			ELSE
				SELECT hb.title_e AS title, hb.Stars, h.photourl, h.lowprice, h.highprice, hb.pid, 
						hb.CheckIn, hb.CheckOut,
						hb.address1, hb.address2, hb.currency, hb.photourl, hb.phone, h.Diamond, 
						hb.country,
						h_city.remark city,
						h_province.remark as state,
						h.subtitle_e as subtitle, hb.holdtime, hb.fax, h.pid, hb.fop, hb.zip, h.groupid
				FROM [h_baseinfo] hb
				JOIN [Hotel] h ON h.Hotel_ID = hb.Hotel_ID
				JOIN h_city ON h.cityid = h_city.CityID
				JOIN h_Province ON h_city.ProvinceID = h_Province.ProvinceID
				WHERE hb.pid = @i_PID AND hb.languagetype = @i_Lan
				
		END
	ELSE
		BEGIN
			IF @i_Lan = 0

				SELECT hb.title, hb.Stars, h.photourl, h.lowprice, h.highprice, hb.pid, hb.country, hb.CheckIn, hb.CheckOut,
						hb.address1, hb.address2, hb.currency, hb.photourl, hb.phone, h.Diamond, hb.city, hb.state, h.subtitle, hb.holdtime, hb.fax, h.pid, hb.fop, hb.zip, h.groupid
				FROM [h_baseinfo] hb
				JOIN [Hotel] h ON h.Hotel_ID = hb.Hotel_ID
				WHERE hb.Hotel_ID = @i_Hotel_ID AND hb.languagetype = @i_Lan
			ELSE
				SELECT hb.title_e AS title, hb.Stars, h.photourl, h.lowprice, h.highprice, hb.pid, 
						hb.CheckIn, hb.CheckOut,
						hb.address1, hb.address2, hb.currency, hb.photourl, hb.phone, h.Diamond, 
						hb.country,
						h_city.remark city,
						h_province.remark as state,
						h.subtitle_e as subtitle, hb.holdtime, hb.fax, h.pid, hb.fop, hb.zip, h.groupid
				FROM [h_baseinfo] hb
				JOIN [Hotel] h ON h.Hotel_ID = hb.Hotel_ID
				JOIN h_city ON h.cityid = h_city.CityID
				JOIN h_Province ON h_city.ProvinceID = h_Province.ProvinceID
				WHERE hb.Hotel_ID = @i_Hotel_ID AND hb.languagetype = @i_Lan
		END
go


create procedure dbo.sp_GetPlanCodeDFBCO (
 	@v_PID varchar(4000),
 	@v_PriceRange varchar(50),
 	@dt_CheckIn datetime,
 	@dt_CheckOut datetime,
 	@v_RateCode varchar(4000), 
 	@i_Languagetype int = 1,
 	@v_Mask_Status varchar(20) = '''N'''
 ) as
DECLARE @v_stemp varchar(6000)
	
	SET @v_stemp ='SELECT DISTINCT c.plancode, c.ratecode, c.roomcode, c.Property_id, c.priceNoTax, 
								   c.avstat, c.minlos, c.maxlos, c.gua, c.cxl, c.cutoff, c.allotment, c.availdate, p.roomname 
				   FROM H_cache as c
				   JOIN h_plan as p ON c.property_id = p.property_id AND c.plancode = p.plancode '
	
	IF @i_Languagetype > 0
		SET @v_stemp = @v_stemp + 'AND p.languagetype = 1 '
	ELSE
		SET @v_stemp = @v_stemp + 'AND p.languagetype = 0 '


	

	SET @v_stemp = @v_stemp + ' WHERE (c.Property_id IN ('+ @v_PID + ') AND '

	IF (@v_PriceRange != '')
		BEGIN
			declare @MyPriceRange nvarchar(100)

			IF (@v_PriceRange='<=250')
				SET @MyPriceRange ='(c.priceNoTax > 0 and c.priceNoTax <= 250)'
				
			IF (@v_PriceRange='250-400')
				SET @MyPriceRange ='(c.priceNoTax > 250 and c.priceNoTax <= 400)'
				
			IF (@v_PriceRange='400-600')
				SET @MyPriceRange ='(c.priceNoTax > 400 and c.priceNoTax <= 600)'
				
			IF (@v_PriceRange='600-800')
				SET @MyPriceRange ='(c.priceNoTax > 600 and c.priceNoTax <= 800)'
				
			IF (@v_PriceRange='>800')
				SET @MyPriceRange ='c.priceNoTax > 800'

			SET @v_stemp = @v_stemp + @MyPriceRange + ' '
			
		END
	ELSE
		SET @v_stemp = @v_stemp + ' c.priceNoTax > 0 '

	SET @v_stemp = @v_stemp + ' AND c.avstat NOT IN (' + @v_Mask_Status + ') AND (( datediff(hh,getdate(),c.Availdate)+24>=c.cutoff ) AND c.Availdate>= '''+
			CONVERT(varchar(10),@dt_CheckIn, 120) + ''' AND c.Availdate < ''' + CONVERT(varchar(10), @dt_CheckOut, 120) + ''') '

	
	IF (@v_RateCode !='')
		SET @v_stemp = @v_stemp + ' AND ' + @v_RateCode

	SET @v_stemp =@v_stemp + ' ) '
	
	SET @v_stemp = @v_stemp + ' ORDER BY c.plancode, c.availdate'
	

	EXEC (@v_stemp)
go


create procedure dbo.sp_GetPlanRate (
 	@v_PIDCode varchar(400),
 	@dt_CheckIn datetime,
 	@dt_CheckOut datetime
 ) as
DECLARE @v_stemp varchar(8000)

	SET @v_stemp = 'SELECT plancode, ratecode, roomcode, avstat, minlos, maxlos, gua, cxl, cutoff, Property_id, priceNoTax, [ID], Allotment, Availdate FROM H_cache '

	

	IF (@v_PIDCode != '')
		SET @v_stemp = @v_stemp + ' WHERE priceNoTax > 0 AND ' + @v_PIDCode
	ELSE
		SET @v_stemp = @v_stemp + ' WHERE 1=2 '

	SET @v_stemp = @v_stemp + ' AND (Availdate >= ''' + CONVERT(varchar(10), @dt_CheckIn, 120) + ''' AND Availdate < ''' + 
								CONVERT(varchar(10), @dt_CheckOut, 120) + ''') ORDER BY plancode, availdate'

	EXEC(@v_stemp)
go


create procedure dbo.sp_GetRecordByPage @tblName      varchar(255),       
     @fldName      varchar(255),       
     @PageSize     int = 10,           
     @PageIndex    int = 1,            
     @IsReCount    bit = 0,            
     @OrderType    bit = 0,            
     @strWhere     nvarchar(1000) = ''  
declare @strSQL   varchar(6000)       
declare @strTmp   varchar(1000)        
declare @strOrder varchar(400)        

if @OrderType != 0
begin
    set @strTmp = '<(select min'
    set @strOrder = ' order by [' + @fldName +'] desc'
end
else
begin
    set @strTmp = '>(select max'
    set @strOrder = ' order by [' + @fldName +'] asc'
end

set @strSQL = 'select top ' + str(@PageSize) + ' * from ['
    + @tblName + '] where [' + @fldName + ']' + @strTmp + '(['
    + @fldName + ']) from (select top ' + str((@PageIndex-1)*@PageSize) + ' ['
    + @fldName + '] from [' + @tblName + ']' + @strOrder + ') as tblTmp)'
    + @strOrder

if @strWhere != ''
    set @strSQL = 'select top ' + str(@PageSize) + ' * from ['
        + @tblName + '] where [' + @fldName + ']' + @strTmp + '(['
        + @fldName + ']) from (select top ' + str((@PageIndex-1)*@PageSize) + ' ['
        + @fldName + '] from [' + @tblName + '] where ' + @strWhere + ' '
        + @strOrder + ') as tblTmp) and ' + @strWhere + ' ' + @strOrder

if @PageIndex = 1
begin
    set @strTmp =''
    if @strWhere != ''
        set @strTmp = ' where ' + @strWhere

    set @strSQL = 'select top ' + str(@PageSize) + ' * from ['
        + @tblName + ']' + @strTmp + ' ' + @strOrder
end

if @IsReCount != 0
    set @strSQL = 'select count(*) as Total from [' + @tblName + ']'+' where ' + @strWhere

exec (@strSQL)
go


create procedure dbo.sp_Get_Hotel_Detail (
 	@i_Hotel_ID int,
 	@i_Lan int = 0 
 ) as
IF @i_Lan = 0

		SELECT hb.title, hb.Stars, h.photourl, hb.lowprice, hb.highprice, hb.pid,
				hb.address1, hb.address2, hb.currency, hb.photourl, hb.phone, h.Diamond, hb.city, hb.state 
		FROM [h_baseinfo] hb
		JOIN [Hotel] h ON h.Hotel_ID = hb.Hotel_ID
		WHERE hb.Hotel_ID = @i_Hotel_ID
	ELSE
		SELECT hb.title_e, hb.Stars, h.photourl, hb.lowprice, hb.highprice, hb.pid,
				hb.address1, hb.address2, hb.currency, hb.photourl, hb.phone, h.Diamond, hb.city, hb.state 
		FROM [h_baseinfo] hb
		JOIN [Hotel] h ON h.Hotel_ID = hb.Hotel_ID
		WHERE hb.Hotel_ID = @i_Hotel_ID
go


create procedure dbo.sp_HCMS_Add_Plan (
 	@i_PID int,
 	@v_PlanCode varchar(50),
 	@v_RoomCode varchar(50),
 	@v_PlanName varchar(100),
 	@v_PlanDesc varchar(500) = null,
 	@i_Language int = 0
 ) as
IF NOT EXISTS(SELECT 1 FROM HCRS_Plan WHERE property_id = @i_PID 
					AND plancode = @v_PlanCode AND RoomCode = @v_RoomCode 
					AND Languagetype = @i_Language)
					
		INSERT INTO HCRS_Plan(property_id, plancode, roomcode, planname, plandesc, updatetime, type, languagetype, available)
		VALUES(@i_PID, @v_PlanCode, @v_RoomCode, @v_PlanName, @v_PlanDesc, getdate(), 'plan', @i_Language, 1)
	ELSE
		UPDATE HCRS_Plan SET planname = @v_PlanName,  
						  plandesc = @v_PlanDesc,
						  available = 1
				WHERE property_id = @i_PID 
				  AND plancode = @v_PlanCode AND RoomCode = @v_RoomCode 
				  AND Languagetype = @i_Language
go


create procedure dbo.sp_PageView @sql  ntext, 
 	 @PageCurrent int=1, 
 	 @PageSize    int=10, 
 	 @PageCount   int OUTPUT as
SET NOCOUNT ON

 DECLARE @p1 int

 EXEC sp_cursoropen 
  @cursor=@p1 OUTPUT,
  @stmt=@sql,
  @scrollopt=1,
  @ccopt=1,
  @rowcount=@PageCount OUTPUT

 
 IF ISNULL(@PageSize,0) < 1 
	 SET @PageSize= 10
	 SET @PageCount= (@PageCount + @PageSize-1) / @PageSize

 IF ISNULL(@PageCurrent,0)<1 OR ISNULL(@PageCurrent,0) > @PageCount
 	SET @PageCurrent = 1
 ELSE 
 	SET @PageCurrent=(@PageCurrent-1)*@PageSize+1

 
 EXEC sp_cursorfetch @p1,16,@PageCurrent,@PageSize
 
 
 EXEC sp_cursorclose @p1
go


create procedure dbo.sp_SearchHotel (
 	@Title nvarchar(50),
 	@City int,
 	@District int,
 	@Commercial int,
 	@CheckIn datetime,
 	@CheckOut datetime,
 	@PriceRange nvarchar(50),
 	@AirPortDistance int,
 	@Stars int,
 	@hotelGeography nvarchar(2000),
 	@AirPortCode nvarchar(50),
 	@ConfirmationType nvarchar(50),
 	@Plan nvarchar(500), 
 	@GroupID nvarchar(2000), 
 	@PageSize int=10, 
 	@CurPage int=1, 
 	@doCount int, 
 	@i_Lan int = 1 
 ) as
declare @MyTitle nvarchar(50)
    
    set @Title=replace(@Title,'''','''''') 
    set @Title=replace(@Title,'--','') 
    set @Title=replace(@Title,';','') 
set @MyTitle = '%'+@Title+'%'


    
   
   
    



declare @s varchar(6000) 
declare @stemp varchar(6000) 

if (@doCount != 0)
	begin 
		set @s ='select count(*) as Total from dbo.Hotel '
	end
else
	begin
		declare @PageIndex int
		set @PageIndex=@CurPage*@PageSize
		set @s ='select  top ' + cast(@PageSize as nvarchar(20)) + ' * from (select top ' + cast(@PageSize as nvarchar(20)) + ' * from (select top ' +cast(@PageIndex as nvarchar(20)) + ' * from dbo.Hotel '
	end

if (@GroupID != '')  
	begin 
		if @i_Lan = 0
			set @s =@s+' where  Passed=1 and  '+ @GroupID
		else
			set @s =@s+' where  enPassed=1 and  '+ @GroupID
	end
else
	begin

		if @i_Lan = 0
			set @s =@s+' where passed=1 '
		else
			set @s =@s+' where enPassed=1 '
	end

set @stemp =''


if (@Title!='')
set @stemp =@stemp+'and (Title like '''+@MyTitle+''' or Title_e like '''+@MyTitle+''' or keywords like ''%'+@MyTitle+'%'' )'

if (@Stars!=10)
	begin
		if(@Stars=0)
			set @stemp =@stemp+' and (Stars =0 and Diamond=0)'
		else
			set @stemp =@stemp+' and ((Stars ='+ cast(@Stars as varchar)+' and Diamond=0)  or (Diamond='+ cast(@Stars as varchar)+' and Stars=0))'
	end

if (@hotelGeography!='')
set @stemp =@stemp+' and address1 like''%'+@hotelGeography+'%'''

	


	
	
	

if (@City!=-1)
set @stemp=@stemp+' and cityid='+ cast(@City as varchar)

if (@District!=-1)
set @stemp=@stemp+' and districtid='+ cast(@District as varchar)

if (@Commercial!=-1)
set @stemp=@stemp+' and commercialid='+ cast(@Commercial as varchar)



set @stemp =@stemp+ ' and (pid in(select distinct property_id from h_cache where '
if (@Plan!='')
	begin
	set @stemp =@stemp+@Plan+ '  and  '
	end
if (@PriceRange!='')
begin
	declare @MyPriceRange nvarchar(100)

	if (@PriceRange='<=250')
	set @MyPriceRange ='priceNoTax>0 and priceNoTax<= 250'
	if (@PriceRange='250-400')
	set @MyPriceRange ='priceNoTax>250 and priceNoTax<=400'
	if (@PriceRange='400-600')
	set @MyPriceRange ='priceNoTax>400 and priceNoTax<=600'
	if (@PriceRange='600-800')
	set @MyPriceRange ='priceNoTax>600 and priceNoTax<=800'
	if (@PriceRange='>800')
	set @MyPriceRange ='priceNoTax> 800'

	set @stemp =@stemp +@MyPriceRange+' '
	
end
else
begin
set @stemp =@stemp+ '  priceNoTax>0 '
end

set @stemp =@stemp+ '  and avstat!=''N''  and (datediff(hh,getdate(),Availdate)+24>=cutoff)  and  Availdate>= '''+convert(varchar(10),@CheckIn,120)+''' AND Availdate<'''+convert(varchar(10),@CheckOut,120)+''') )'


declare @v_PageRank varchar(20)

if @i_Lan = 0
	set @v_PageRank = 'pagerank'
else
	set @v_PageRank = 'enPagerank'




if (@doCount =0)
	begin
	set @s =@s+@stemp+ ' order by credit desc, ' + @v_PageRank + ' desc,hotel_id ) as aa  order by credit, '+ @v_PageRank + 
				' ,hotel_id desc) as aa order by credit desc, ' + @v_PageRank + ' desc,hotel_id'
	end
else
	set @s =@s+@stemp
	
exec ( @s )
go


create procedure dbo.sp_Search_Hotel (
 	@Title nvarchar(50),
 	@City int,
 	@District int,
 	@Commercial int,
 	@CheckIn datetime,
 	@CheckOut datetime,
 	@PriceRange nvarchar(50),
 	@AirPortDistance int,
 	@Stars int,
 	@hotelGeography nvarchar(2000),
 	@AirPortCode nvarchar(50),
 	@ConfirmationType nvarchar(50),
 	@Plan nvarchar(500), 
 	@GroupID nvarchar(2000), 
 	@PageSize int=10, 
 	@CurPage int=1, 
 	@i_Lan int = 1 
 ) as
declare @MyTitle nvarchar(50)

	
	set @Title=replace(@Title,'''','''''') 
	set @Title=replace(@Title,'--','') 
	set @Title=replace(@Title,';','') 

	set @MyTitle = '%' + @Title + '%'
	

	declare @v_count_head varchar(100)
	declare @v_head varchar(400)

	declare @stemp varchar(6000) 

	set @stemp = ''

	set @v_count_head = 'select count(*) as Total from dbo.Hotel '

	declare @PageIndex int
	set @PageIndex=@CurPage * @PageSize
	
	DECLARE @v_Colums varchar(200)
	
	SET @v_Colums = ' pid, hotel_id, title_e, title, credit, Stars, Diamond, enPagerank,enPassed, GroupID, cityid, ServiceCharge '
	
	set @v_head ='select top ' + cast(@PageSize as nvarchar(20)) + @v_Colums + ' from (select top ' + 
		cast(@PageSize as nvarchar(20)) + @v_Colums + ' from (select top ' +cast(@PageIndex as nvarchar(20))  + @v_Colums + ' from dbo.Hotel '


	

	if (@GroupID != '')
		begin 
			if @i_Lan = 0
				set @stemp = @stemp + ' where Passed=1 and '+ @GroupID
			else
				set @stemp = @stemp + ' where enPassed=1 and '+ @GroupID
		end
	else
		begin

			if @i_Lan = 0
				set @stemp = @stemp + ' where passed=1 '
			else
				set @stemp = @stemp + ' where enPassed=1 '
		end


	
	if (@Title != '')
		BEGIN
			IF @i_Lan = 0
				set @stemp = @stemp + 'and (Title like '''+ @MyTitle + ''' or keywords like ''%'+ @MyTitle + '%'')'
			ELSE
				set @stemp = @stemp + 'and (Title_e like '''+ @MyTitle + ''' or keywords like ''%'+ @MyTitle + '%'')'
		END
		
	
	if (@Stars!=10)
		begin
			if(@Stars=0)
				set @stemp =@stemp+' and (Stars =0 and Diamond=0)'
			else
				set @stemp =@stemp+' and ((Stars ='+ cast(@Stars as varchar)+' and Diamond=0)  or (Diamond='+ cast(@Stars as varchar)+' and Stars=0))'
		end
		
	
	if (@hotelGeography!='')
		set @stemp =@stemp+' and address1 like''%'+@hotelGeography+'%'''

	
	if (@City != -1)
		set @stemp = @stemp+' and cityid='+ cast(@City as varchar)
	
	
	if (@District != -1)
		set @stemp=@stemp+' and districtid='+ cast(@District as varchar)
	
	
	if (@Commercial != -1)
		set @stemp=@stemp+' and commercialid='+ cast(@Commercial as varchar)
		
	

	
	DECLARE @v_HighspeedQuery varchar(2000)
	
	SET @v_HighspeedQuery = @stemp + ' AND (SELECT COUNT(*) FROM (SELECT TOP 1 * FROM h_cache WHERE property_id = dbo.Hotel.pid AND ' 
	
	set @stemp = @stemp + ' and (pid in(select distinct property_id from h_cache where '
	
	
	if (@Plan != '')
		begin
			set @stemp =@stemp + @Plan + ' and '
			SET @v_HighspeedQuery = @v_HighspeedQuery + @Plan + ' AND '
		end
	
	if (@PriceRange != '')
		begin
			declare @MyPriceRange nvarchar(100)

			if (@PriceRange='<=250')
				set @MyPriceRange ='priceNoTax>=0 and priceNoTax<= 250'
				
			if (@PriceRange='250-400')
				set @MyPriceRange ='priceNoTax>250 and priceNoTax<=400'
				
			if (@PriceRange='400-600')
				set @MyPriceRange ='priceNoTax>400 and priceNoTax<=600'
				
			if (@PriceRange='600-800')
				set @MyPriceRange ='priceNoTax>600 and priceNoTax<=800'
				
			if (@PriceRange='>800')
				set @MyPriceRange ='priceNoTax> 800'

			set @stemp = @stemp + @MyPriceRange + ' '
			SET @v_HighspeedQuery = @v_HighspeedQuery + @MyPriceRange + ' '
			
		end
	else
		begin
			set @stemp = @stemp + ' priceNoTax>=0 '
			SET @v_HighspeedQuery = @v_HighspeedQuery + ' priceNoTax>=0 '
		end

	set @stemp = @stemp + ' and avstat!=''N'' and (datediff(hh, getdate(), Availdate) + 24 >= cutoff) and Availdate>= ''' +
		convert(varchar(10),@CheckIn,120) + ''' AND Availdate<'''+convert(varchar(10),@CheckOut,120) + ''') )'

	SET @v_HighspeedQuery = @v_HighspeedQuery + ' and avstat!=''N'' and (datediff(hh, getdate(), Availdate) + 24 >= cutoff) and Availdate>= ''' +
		CONVERT(varchar(10),@CheckIn,120) + ''' AND Availdate<'''+convert(varchar(10),@CheckOut,120) + ''')'

	declare @v_PageRank varchar(20)

	if @i_Lan = 0
		set @v_PageRank = 'pagerank'
	else
		set @v_PageRank = 'enPagerank'


	set @v_HighspeedQuery = @v_HighspeedQuery + ' as che) > 0 '


	exec(@v_head + @stemp + ' order by credit desc, ' + @v_PageRank + 
		' desc,hotel_id ) as aa  order by credit, ' + @v_PageRank + 
		' ,hotel_id desc) as aa order by credit desc, ' + @v_PageRank + ' desc,hotel_id;'+
		@v_count_head + @v_HighspeedQuery)
go


create procedure dbo.sp_Search_Hotel_3 (
 	@v_Title varchar(200) = null,
 	@i_City int = -1,
 	@i_District int = -1,
 	@i_Commercial int = -1,
 	@dt_CheckIn datetime = null,
 	@dt_CheckOut datetime = null,
 	@v_PriceRange varchar(200) = null,
 	@i_Stars int = 10,
 	
 
 	@v_Plan varchar(2000),
 	@v_GroupID varchar(2000),
 	
 	@v_HotelType varchar(20) = null,
 	
 	@i_PageSize int = 10, 
 	@i_CurPage int = 1, 
 	@i_Lan int = 1, 
 	@v_Mask_Status varchar(20) = '''N''',
 	
 	@i_Corp int = null, 
 	@i_Flag int = 0 
 ) as
DECLARE @v_MyTitle nvarchar(50)

	
	
	SET @v_Title = replace(@v_Title, '''', '''''')
	SET @v_Title = replace(@v_Title,'--','') 
	SET @v_Title = replace(@v_Title,';','')
	
	SET @v_MyTitle = '%' + @v_Title + '%'
	

	DECLARE @v_count_head varchar(100)
	DECLARE @v_head varchar(400)

	DECLARE @stemp varchar(6000) 

	SET @stemp = ''

	SET @v_count_head = 'SELECT COUNT(*) as Total FROM dbo.Hotel '

	DECLARE @i_PageIndex int
	SET @i_PageIndex = @i_CurPage * @i_PageSize
	
	DECLARE @v_Colums varchar(200)
	
	SET @v_Colums = ' pid, hotel_id, title_e, title, credit, Stars, Diamond, enPagerank,enPassed, GroupID, cityid, ServiceCharge '
	
	SET @v_head ='SELECT TOP ' + cast(@i_PageSize as nvarchar(20)) + @v_Colums + ' FROM (SELECT TOP ' + 
		cast(@i_PageSize as nvarchar(20)) + @v_Colums + ' FROM (SELECT TOP ' +cast(@i_PageIndex as nvarchar(20))  + @v_Colums + ' FROM dbo.Hotel '

	

	IF (@v_GroupID != '')
		BEGIN 
			IF @i_Lan = 0
				SET @stemp = @stemp + ' WHERE Passed = 1 AND ' + @v_GroupID
			ELSE
				SET @stemp = @stemp + ' WHERE enPassed = 1 AND ' + @v_GroupID
		END
	ELSE
		BEGIN

			IF @i_Lan = 0
				SET @stemp = @stemp + ' WHERE passed = 1 '
			ELSE
				SET @stemp = @stemp + ' WHERE enPassed = 1 '
		END


	
	IF (@v_Title != '' AND @v_Title IS NOT NULL)
		BEGIN
			IF @i_Lan = 0
				SET @stemp = @stemp + ' AND (Title like '''+ @v_MyTitle + ''')'
				
			ELSE
				SET @stemp = @stemp + ' AND (Title_e like '''+ @v_MyTitle + ''')'
				
				
		END
		
	
	IF (@i_Stars != 10)
		BEGIN
			IF(@i_Stars = 0)
				SET @stemp = @stemp + ' AND (Stars = 0 AND Diamond = 0)'
			ELSE
				SET @stemp = @stemp + ' AND ((Stars ='+ cast(@i_Stars as varchar) + 
								      ' AND Diamond = 0) OR (Diamond = '+ cast(@i_Stars as varchar) + ' AND Stars = 0))'
		END
		
	
	
	

	
	IF (@i_City != -1)
		SET @stemp = @stemp + ' AND cityid = '+ cast(@i_City as varchar)
	
	
	IF (@i_District != -1)
		SET @stemp=@stemp + ' AND districtid='+ cast(@i_District as varchar)
	
	
	IF (@i_Commercial != -1)
		SET @stemp=@stemp + ' AND commercialid='+ cast(@i_Commercial as varchar)
	
	
	IF (@v_HotelType IS NOT NULL)
		
		SET @stemp = @stemp + ' AND (SELECT TOP 1 proptype FROM h_baseinfo hb WHERE hb.hotel_id = Hotel.Hotel_ID AND languagetype = ' + str(@i_Lan) + ' ) = ''' + @v_HotelType + ''''
	
	IF @i_Corp IS NOT NULL
		BEGIN
			DECLARE @v_Corp_Hotel_IDs varchar(6000)

			SELECT @v_Corp_Hotel_IDs = CASE WHEN customhotel IS NULL OR LEN(customhotel) < 1 THEN '0' 
					ELSE LEFT(customhotel, LEN(customhotel) - 1) 
					END
				    FROM corp WHERE corp_id = @i_Corp
			
			IF @i_Flag = 1
				SET @stemp = @stemp + ' AND Hotel_ID IN(' + @v_Corp_Hotel_IDs + ')'	
			ELSE IF @i_Flag = 2
				SET @stemp = @stemp + ' AND Hotel_ID NOT IN(' + @v_Corp_Hotel_IDs + ')'	
		END
	

	DECLARE @v_HighspeedQuery varchar(2000)
	
	SET @v_HighspeedQuery = @stemp + ' AND (SELECT COUNT(property_id) FROM (SELECT TOP 1 property_id FROM h_cache WHERE property_id = dbo.Hotel.pid AND ' 
	
	SET @stemp = @stemp + ' AND (pid IN(SELECT DISTINCT property_id FROM h_cache WHERE '
	
	
	IF (@v_Plan != '')
		BEGIN
			SET @stemp = @stemp + @v_Plan + ' AND '
			SET @v_HighspeedQuery = @v_HighspeedQuery + @v_Plan + ' AND '
		END
		
	
	IF (@v_PriceRange != '' AND @v_PriceRange IS NOT NULL)
		BEGIN
			DECLARE @v_MyPriceRange nvarchar(100)

			IF (@v_PriceRange = '<=250')
				SET @v_MyPriceRange = ' priceNoTax>0 AND priceNoTax<= 250'
				
			IF (@v_PriceRange = '250-400')
				SET @v_MyPriceRange = ' priceNoTax>250 AND priceNoTax<=400'
				
			IF (@v_PriceRange = '400-600')
				SET @v_MyPriceRange = ' priceNoTax>400 AND priceNoTax<=600'
				
			IF (@v_PriceRange = '600-800')
				SET @v_MyPriceRange = ' priceNoTax>600 AND priceNoTax<=800'
				
			IF (@v_PriceRange = '>800')
				SET @v_MyPriceRange = ' priceNoTax> 800'

			SET @stemp = @stemp + @v_MyPriceRange + ' '
			SET @v_HighspeedQuery = @v_HighspeedQuery + @v_MyPriceRange + ' '
			
		END
	ELSE
		BEGIN
			SET @stemp = @stemp + ' priceNoTax > 0 '
			SET @v_HighspeedQuery = @v_HighspeedQuery + ' priceNoTax > 0 '
		END

	
	SET @stemp = @stemp + ' AND avstat NOT IN (' + @v_Mask_Status + ')'
	SET @v_HighspeedQuery = @v_HighspeedQuery + ' AND avstat NOT IN (' + @v_Mask_Status + ')'
	
	IF(@dt_CheckOut IS NOT NULL AND @dt_CheckIn IS NOT NULL)
		BEGIN
		
			SET @stemp = @stemp + ' AND (datediff(hh, getdate(), Availdate) + 24 >= cutoff) AND Availdate>= ''' +
				CONVERT(varchar(10),@dt_CheckIn,120) + ''' AND Availdate<''' + CONVERT(varchar(10),@dt_CheckOut,120) + '''))'

			SET @v_HighspeedQuery = @v_HighspeedQuery + ' AND (datediff(hh, getdate(), Availdate) + 24 >= cutoff) AND Availdate>= ''' +
				CONVERT(varchar(10),@dt_CheckIn,120) + ''' AND Availdate<''' + CONVERT(varchar(10),@dt_CheckOut,120) + ''')'
		
		END
	ELSE
		BEGIN
			SET @stemp = @stemp + '))'
			SET @v_HighspeedQuery = @v_HighspeedQuery + ')'
		END
		
	DECLARE @v_PageRank varchar(20)

	IF @i_Lan = 0
		SET @v_PageRank = 'pagerank'
	ELSE
		SET @v_PageRank = 'enPagerank'


	SET @v_HighspeedQuery = @v_HighspeedQuery + ' as che) > 0 '


	EXEC(@v_head + @stemp + ' order by credit desc, ' + @v_PageRank + 
		' desc,hotel_id ) as aa  order by credit, ' + @v_PageRank + 
		' ,hotel_id desc) as aa order by credit desc, ' + @v_PageRank + ' desc,hotel_id;'+
		@v_count_head + @v_HighspeedQuery)
go


create procedure dbo.sp_UpdateCache (
 	@i_Property_ID int, 
 	@v_PlanCode varchar(100), 
 	@dt_AvailDate datetime,  
 	@d_SingleRate decimal(8, 2), 
 	@d_Doublerate decimal(8, 2), 
 	@d_Triplerate decimal(8, 2), 
 	@d_Quadrate decimal(8, 2),  
 	@d_Extraadult decimal(8, 2), 
 	@d_Extrachildren decimal(8, 2), 
 	@i_Allotment int, 
 	@i_AllotMax int,  
 	@i_AvStat int, 
 	@i_MaxLos int, 
 	@i_MinLos int, 
 	@v_RateCode varchar(50), 
 	@v_RoomCode varchar(50), 
 	@v_PlanName varchar(200), 
 	@v_RoomName varchar(200), 
 	@v_RoomDesc varchar(2000) = null, 
 	@v_PlanDesc varchar(2000) = null, 
 	@v_Type varchar(50) = null,
 	
 	@chr_Tcode char(10), 
 	@dt_From datetime = null, 
 	@dt_To datetime = null, 
 	@v_Gua varchar(50),  
 	@v_Cxl varchar(50), 
 	@d_PriceNoTax decimal(9,2), 
 	@i_CutOff int,
 	
 	@i_LanguageType int = 1
 ) as
IF NOT EXISTS(SELECT TOP 1 * FROM h_cache WHERE property_id = @i_Property_ID AND plancode = @v_PlanCode AND availdate = @dt_AvailDate)
		BEGIN
			
			
			INSERT INTO h_cache(Property_id, plancode, 
								Availdate,  singlerate, 
								doublerate, triplerate, 
								quadrate,  
								extraadult, extrachildren, 
								Allotment, AllotMax,  AvStat, 
								MaxLos, MinLos, 
								RateCode, RoomCode, Tcode, 
								T_from, T_to, Gua,  Cxl, 
								PriceNoTax, cutOff)
			VALUES(	@i_Property_ID, @v_PlanCode, 
				    @dt_AvailDate, @d_SingleRate, 
					@d_Doublerate, @d_Triplerate, 
					@d_Quadrate,  
					@d_Extraadult, @d_Extrachildren, 
					@i_Allotment, @i_AllotMax, @i_AvStat, 
					@i_MaxLos, @i_MinLos, 
					@v_RateCode, @v_RoomCode, @chr_Tcode, 
					@dt_From, @dt_To, @v_Gua,  @v_Cxl, 
					@d_PriceNoTax, @i_CutOff)
			
			
		END
	ELSE
		BEGIN
			
			UPDATE h_cache SET 
			singlerate = @d_SingleRate, 
			doublerate = @d_Doublerate, 
			triplerate = @d_Triplerate, 
			quadrate = @d_Quadrate,  
			extraadult = @d_Extraadult, 
			extrachildren = @d_Extrachildren, 
			Allotment = @i_Allotment, 
			AllotMax = @i_AllotMax,  
			AvStat = @i_AvStat, 
			MaxLos = @i_MaxLos, 
			MinLos = @i_MinLos, 
			RateCode = @v_RateCode, 
			RoomCode = @v_RoomCode, 
			Tcode = @chr_Tcode, 
			T_from = @dt_From, 
			T_to = @dt_To, 
			Gua = @v_Gua,  
			Cxl = @v_Cxl, 
			PriceNoTax = @d_PriceNoTax, 
			cutOff = @i_CutOff
			WHERE property_id = @i_Property_ID AND plancode = @v_PlanCode AND availdate = @dt_AvailDate
			
		END
		
	
	
	IF NOT EXISTS(SELECT TOP 1 * FROM h_plan WHERE property_id = @i_Property_ID AND plancode = @v_PlanCode AND languagetype = @i_LanguageType)
		BEGIN
			INSERT INTO h_plan (Property_id, plancode, roomCode, planname, 
								roomname, roomdesc, plandesc, type, languagetype)
						VALUES(@i_Property_ID, @v_PlanCode, @v_RoomCode, @v_PlanName, 
								@v_RoomName, @v_RoomDesc, @v_PlanDesc, @v_Type, @i_LanguageType)
			
		END
	ELSE
		BEGIN
			UPDATE h_plan SET roomCode = @v_RoomCode, 
							  planname = @v_PlanName, 
							  roomname = @v_RoomName, 
							  roomdesc = @v_RoomDesc, 
							  plandesc = @v_PlanDesc, 
							  type = @v_Type
			WHERE property_id = @i_Property_ID AND plancode = @v_PlanCode AND languagetype = @i_LanguageType				  		
		END
go


create procedure dbo.sp_connect_oralce <@arg> <type> as
declare <@var> <type>
begin

end
go


create procedure dbo.usp_PagingLarge @TableNames VARCHAR(200),    
 @PrimaryKey VARCHAR(100),    
 @Fields    VARCHAR(200),        
 @PageSize INT,            
 @CurrentPage INT,        
 @Filter VARCHAR(200) = '',    
 @Group VARCHAR(200) = '',    
 @Order VARCHAR(200) = ''    
BEGIN
    DECLARE @SortColumn VARCHAR(200)
    DECLARE @Operator CHAR(2)
    DECLARE @SortTable VARCHAR(200)
    DECLARE @SortName VARCHAR(200)
    IF @Fields = ''
        SET @Fields = '*'
    IF @Filter = ''
        SET @Filter = 'WHERE 1=1'
    ELSE
        SET @Filter = 'WHERE ' +  @Filter
    IF @Group <>''
        SET @Group = 'GROUP BY ' + @Group

    IF @Order <> ''
    BEGIN
        DECLARE @pos1 INT, @pos2 INT
        SET @Order = REPLACE(REPLACE(@Order, ' asc', ' ASC'), ' desc', ' DESC')
        IF CHARINDEX(' DESC', @Order) > 0
            IF CHARINDEX(' ASC', @Order) > 0
            BEGIN
                IF CHARINDEX(' DESC', @Order) < CHARINDEX(' ASC', @Order)
                    SET @Operator = '<='
                ELSE
                    SET @Operator = '>='
            END
            ELSE
                SET @Operator = '<='
        ELSE
            SET @Operator = '>='
        SET @SortColumn = REPLACE(REPLACE(REPLACE(@Order, ' ASC', ''), ' DESC', ''), ' ', '')
        SET @pos1 = CHARINDEX(',', @SortColumn)
        IF @pos1 > 0
            SET @SortColumn = SUBSTRING(@SortColumn, 1, @pos1-1)
        SET @pos2 = CHARINDEX('.', @SortColumn)
        IF @pos2 > 0
        BEGIN
            SET @SortTable = SUBSTRING(@SortColumn, 1, @pos2-1)
            IF @pos1 > 0 
                SET @SortName = SUBSTRING(@SortColumn, @pos2+1, @pos1-@pos2-1)
            ELSE
                SET @SortName = SUBSTRING(@SortColumn, @pos2+1, LEN(@SortColumn)-@pos2)
        END
        ELSE
        BEGIN
            SET @SortTable = @TableNames
            SET @SortName = @SortColumn
        END
    END
    ELSE
    BEGIN
        SET @SortColumn = @PrimaryKey
        SET @SortTable = @TableNames
        SET @SortName = @SortColumn
        SET @Order = @SortColumn
        SET @Operator = '>='
    END

    DECLARE @type varchar(50)
    DECLARE @prec int
    SELECT @type=t.name, @prec=c.prec
    FROM sysobjects o 
    JOIN syscolumns c on o.id=c.id
    JOIN systypes t on c.xusertype=t.xusertype
    WHERE o.name = @SortTable AND c.name = @SortName
    IF CHARINDEX('char', @type) > 0
    SET @type = @type + '(' + CAST(@prec AS varchar) + ')'

    DECLARE @TopRows INT
    SET @TopRows = @PageSize * @CurrentPage + 1
    print @TopRows
    print @Operator
    EXEC('
        DECLARE @SortColumnBegin ' + @type + '
        SET ROWCOUNT ' + @TopRows + '
        SELECT @SortColumnBegin=' + @SortColumn + ' FROM  ' + @TableNames + ' ' + @Filter + ' ' + @Group + ' ORDER BY ' + @Order + '
        SET ROWCOUNT ' + @PageSize + '
        SELECT ' + @Fields + ' FROM  ' + @TableNames + ' ' + @Filter  + ' AND ' + @SortColumn + '' + @Operator + '@SortColumnBegin ' + @Group + ' ORDER BY ' + @Order + '    
    ')    
END
go
